diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000000..9a56dca7f02 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ + + +##### Description + + + +##### Swagger-codegen version + + + +##### Swagger declaration file content or url + + + +##### Command line used for generation + + + +##### Steps to reproduce + + + +##### Related issues + + + +##### Suggest a Fix + + + diff --git a/.gitignore b/.gitignore index 2e1d1355309..3118eafbcfd 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ samples/server-generator/scalatra/target samples/server-generator/scalatra/output/.history # nodejs +**/node_modules/ samples/server-generator/node/output/node_modules samples/server/petstore/nodejs/node_modules samples/server/petstore/nodejs-server/node_modules @@ -62,6 +63,12 @@ samples/client/petstore/java/jersey2/.gradle/ samples/client/petstore/java/jersey2/build/ samples/client/petstore/java/okhttp-gson/.gradle/ samples/client/petstore/java/okhttp-gson/build/ +samples/client/petstore/java/feign/build/ +samples/client/petstore/java/retrofit/build/ +samples/client/petstore/java/retrofit2/build/ +samples/client/petstore/java/retrofit2rx/build/ +samples/client/petstore/java/default/build/ +samples/client/petstore/scala/build/ #PHP samples/client/petstore/php/SwaggerClient-php/composer.lock @@ -88,6 +95,7 @@ samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddat # C# *.csproj.user +samples/client/petstore/csharp/SwaggerClient/IO.Swagger.userprefs samples/client/petstore/csharp/SwaggerClientTest/.vs samples/client/petstore/csharp/SwaggerClientTest/obj samples/client/petstore/csharp/SwaggerClientTest/bin @@ -104,6 +112,7 @@ samples/client/petstore/csharp/SwaggerClient/bin samples/client/petstore/csharp/SwaggerClient/obj/Debug/ samples/client/petstore/csharp/SwaggerClient/bin/Debug/ samples/client/petstore/csharp/SwaggerClient/packages +samples/client/petstore/csharp/SwaggerClient/TestResult.xml # Python *.pyc @@ -116,13 +125,8 @@ samples/client/petstore/python/.venv/ # ts samples/client/petstore/typescript-node/npm/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/dist -samples/client/petstore/typescript-fetch/with-package-metadata/typings -samples/client/petstore/typescript-fetch/default/node_modules -samples/client/petstore/typescript-fetch/default/dist -samples/client/petstore/typescript-fetch/default/typings -samples/client/petstore/typescript-fetch/default-es6/node_modules -samples/client/petstore/typescript-fetch/default-es6/dist -samples/client/petstore/typescript-fetch/default-es6/typings +samples/client/petstore/typescript-node/**/typings +samples/client/petstore/typescript-angular/**/typings +samples/client/petstore/typescript-fetch/**/dist/ +samples/client/petstore/typescript-fetch/**/typings diff --git a/.travis.yml b/.travis.yml index 46bb326da69..1a0be745a6e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,8 @@ services: before_install: # required when sudo: required for the Ruby petstore tests - gem install bundler + - npm install -g typescript + - sudo pip install virtualenv install: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4cf901c2d3f..a40a96f7b38 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,12 +2,10 @@ ## Before submitting an issue + - If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/swagger-api/swagger-codegen#getting-started) - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. - - The issue should contain details on how to repeat the issue, e.g. - - the OpenAPI Spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the OpenAPI Spec cannot be shared publicly, it will be hard for the community to help - - version of Swagger Codegen - - language (`-l` in the command line, e.g. java, csharp, php) - - You can also make a suggestion or ask a question by opening an "issue" + - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - You can also make a suggestion or ask a question by opening an "issue". ## Before submitting a PR @@ -42,11 +40,14 @@ Code change should conform to the programming style guide of the respective lang - Swift: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html - TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines - For other languages, feel free to suggest. You may find the current code base not 100% conform to the coding style and we welcome contributions to fix those. +For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below: +- For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type` +- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit` + ### Testing To add test cases (optional) covering the change in the code generator, please refer to [modules/swagger-codegen/src/test/java/io/swagger/codegen](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/test/java/io/swagger/codegen) diff --git a/README.md b/README.md index bce750740c7..ece108666e1 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.1.7-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.2.0-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) 2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -386,8 +386,66 @@ To control the specific files being generated, you can pass a CSV list of what y -Dmodels=User -DsupportingFiles=StringUtil.java ``` +To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`. +These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`): + +``` +# generate only models (with tests and documentation) +java -Dmodels {opts} + +# generate only models (with tests but no documentation) +java -Dmodels -DmodelDocs=false {opts} + +# generate only User and Pet models (no tests and no documentation) +java -Dmodels=User,Pet -DmodelTests=false {opts} + +# generate only apis (without tests) +java -Dapis -DapiTests=false {opts} + +# generate only apis (modelTests option is ignored) +java -Dapis -DmodelTests=false {opts} +``` + When using selective generation, _only_ the templates needed for the specific generation will be used. +### Ignore file format + +Swagger codegen supports a `.swagger-codegen-ignore` file, similar to `.gitignore` or `.dockerignore` you're probably already familiar with. + +The ignore file allows for better control over overwriting existing files than the `--skip-overwrite` flag. With the ignore file, you can specify individual files or directories can be ignored. This can be useful, for example if you only want a subset of the generated code. + +Examples: + +``` +# Swagger Codegen Ignore +# Lines beginning with a # are comments + +# This should match build.sh located anywhere. +build.sh + +# Matches build.sh in the root +/build.sh + +# Exclude all recursively +docs/** + +# Explicitly allow files excluded by other rules +!docs/UserApi.md + +# Recursively exclude directories named Api +# You can't negate files below this directory. +src/**/Api/ + +# When this file is nested under /Api (excluded above), +# this rule is ignored because parent directory is excluded by previous rule. +!src/**/PetApiTests.cs + +# Exclude a single, nested file explicitly +src/IO.Swagger.Test/Model/AnimalFarmTests.cs +``` + +The `.swagger-codegen-ignore` file must exist in the root of the output directory. + ### Customizing the generator There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc: @@ -608,7 +666,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ - -l silex \ + -l silex-PHP \ -o samples/server/petstore/silex ``` @@ -789,20 +847,25 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Activehours](https://www.activehours.com/) - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) +- [Avenida Compras S.A.](https://www.avenida.com.ar) - [beemo](http://www.beemo.eu) - [bitly](https://bitly.com) - [Cachet Financial](http://www.cachetfinancial.com/) - [CloudBoost](https://www.CloudBoost.io/) - [Cupix](http://www.cupix.com) +- [DBBest Technologies](https://www.dbbest.com) - [DocuSign](https://www.docusign.com) - [Ergon](http://www.ergon.ch/) - [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) +- [GraphHopper](https://graphhopper.com/) +- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Interactive Intelligence](http://developer.mypurecloud.com/) - [LANDR Audio](https://www.landr.com/) - [LiveAgent](https://www.ladesk.com/) +- [Kabuku](http://www.kabuku.co.jp/en) - [Kuary](https://kuary.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) @@ -813,12 +876,15 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [PostAffiliatePro](https://www.postaffiliatepro.com/) - [Reload! A/S](https://reload.dk/) - [REstore](https://www.restore.eu) +- [Revault Sàrl](http://revault.ch) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) +- [SCOOP Software GmbH](http://www.scoop-software.de) - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) - [ThoughtWorks](https://www.thoughtworks.com) - [uShip](https://www.uship.com/) +- [WEXO A/S](https://www.wexo.dk/) - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) @@ -836,13 +902,13 @@ Swaagger Codegen core team members are contributors who have been making signfic | Dart | | | Groovy | | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | -| Java | @cbornet (2016/05/01) @xhh (2016/05/01) | +| Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) | | NodeJS/Javascript | @xhh (2016/05/01) | | ObjC | @mateuszmackowiak (2016/05/09) | | Perl | @wing328 (2016/05/01) | | PHP | @arnested (2016/05/01) | | Python | @scottrw93 (2016/05/01) | -| Ruby | @wing328 (2016/05/01) | +| Ruby | @wing328 (2016/05/01) @zlx (2016/05/22) | | Scala | | | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | | TypeScript (Node) | @Vrolijkx (2016/05/01) | @@ -894,6 +960,7 @@ Here is a list of template creators: * JAX-RS CXF: @hiveship * PHP Lumen: @abcsum * PHP Slim: @jfastnacht + * Ruby on Rails 5: @zlx ## How to join the core team diff --git a/bin/android-petstore-httpclient.sh b/bin/android-petstore-httpclient.sh new file mode 100755 index 00000000000..097484e0410 --- /dev/null +++ b/bin/android-petstore-httpclient.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/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -Dlibrary=httpclient -o samples/client/petstore/android/httpclient" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-petstore.sh b/bin/android-petstore.sh index 72b12f92e55..67256debeb0 100755 --- a/bin/android-petstore.sh +++ b/bin/android-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/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/volley" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh index 063b85f70a1..61c4621a1f6 100755 --- a/bin/java-petstore-feign.sh +++ b/bin/java-petstore-feign.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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh index a715e7ff545..0850bdbb4f4 100755 --- a/bin/java-petstore-jersey2.sh +++ b/bin/java-petstore-jersey2.sh @@ -26,6 +26,9 @@ 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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2 -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main" +rm -rf samples/client/petstore/java/jersey2/src/main +find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh index f656624a6c6..492cd5ff4a4 100755 --- a/bin/java-petstore-okhttp-gson.sh +++ b/bin/java-petstore-okhttp-gson.sh @@ -26,6 +26,8 @@ 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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true" +rm -rf samples/client/petstore/java/okhttp-gson/src/main +find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit.sh b/bin/java-petstore-retrofit.sh index db4001e4c9e..3b370fde7dd 100755 --- a/bin/java-petstore-retrofit.sh +++ b/bin/java-petstore-retrofit.sh @@ -26,6 +26,9 @@ 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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/retrofit/src/main" +rm -rf samples/client/petstore/java/retrofit/src/main +find samples/client/petstore/java/retrofit -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2.sh b/bin/java-petstore-retrofit2.sh index 3fda4df3166..8cf9468c3a1 100755 --- a/bin/java-petstore-retrofit2.sh +++ b/bin/java-petstore-retrofit2.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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2 -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2rx.sh b/bin/java-petstore-retrofit2rx.sh index d714cc33455..af62352c03f 100755 --- a/bin/java-petstore-retrofit2rx.sh +++ b/bin/java-petstore-retrofit2rx.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/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true,hideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index ed80c841df6..be6472d7aad 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -28,4 +28,7 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/default/src/main" +rm -rf samples/client/petstore/java/default/src/main +find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-jersey1-petstore-server.sh b/bin/jaxrs-jersey1-petstore-server.sh new file mode 100755 index 00000000000..8195b02c72b --- /dev/null +++ b/bin/jaxrs-jersey1-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/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/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh index 6436c797e87..3c7e4af91a8 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-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/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey2 -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 513b7535786..df22ea3b595 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-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/swagger-codegen/src/main/resources/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc --additional-properties coreData=true" java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index ef120089f45..0fe89ea39ed 100755 --- a/bin/python-petstore.sh +++ b/bin/python-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/swagger-codegen/src/main/resources/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l python -o samples/client/petstore/python" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l python -o samples/client/petstore/python -DpackageName=petstore_api" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/rails5-petstore-server.sh b/bin/rails5-petstore-server.sh new file mode 100755 index 00000000000..28b3ca3069b --- /dev/null +++ b/bin/rails5-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/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/rails5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-stubs.sh b/bin/spring-stubs.sh new file mode 100755 index 00000000000..3d13f2fe8b9 --- /dev/null +++ b/bin/spring-stubs.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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -o samples/client/petstore/spring-stubs -DinterfaceOnly=true,singleContentTypes=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/springboot-petstore-server.sh b/bin/springboot-petstore-server.sh index 83d810ba595..7fe3ac60e53 100755 --- a/bin/springboot-petstore-server.sh +++ b/bin/springboot-petstore-server.sh @@ -26,6 +26,9 @@ 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/JavaSpringBoot -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -o samples/server/petstore/springboot" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpringBoot -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -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 +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-promisekit.json b/bin/swift-petstore-promisekit.json new file mode 100644 index 00000000000..1211352cc55 --- /dev/null +++ b/bin/swift-petstore-promisekit.json @@ -0,0 +1,7 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient", + "responseAs": "PromiseKit" +} \ No newline at end of file diff --git a/bin/swift-petstore-promisekit.sh b/bin/swift-petstore-promisekit.sh new file mode 100755 index 00000000000..d2787a876a0 --- /dev/null +++ b/bin/swift-petstore-promisekit.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/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore.json b/bin/swift-petstore.json index 700fdeff061..3d9ecfd5d0a 100644 --- a/bin/swift-petstore.json +++ b/bin/swift-petstore.json @@ -1,4 +1,6 @@ { - "projectName": "PetstoreClient", - "responseAs": "PromiseKit" + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient" } \ No newline at end of file diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh index 96433e5b72d..3747b3adca4 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/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh index d39c16d8803..6365b9032a6 100755 --- a/bin/typescript-fetch-petstore-all.sh +++ b/bin/typescript-fetch-petstore-all.sh @@ -1,5 +1,5 @@ #!/bin/sh ./bin/typescript-fetch-petstore-target-es6.sh -./bin/typescript-fetch-petstore-target-with-package-metadata.sh +./bin/typescript-fetch-petstore-with-npm-version.sh ./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh index 3734e7e3449..84a6562eeb6 100755 --- a/bin/typescript-fetch-petstore-target-es6.sh +++ b/bin/typescript-fetch-petstore-target-es6.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/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.json b/bin/typescript-fetch-petstore-with-npm-version.json similarity index 100% rename from bin/typescript-fetch-petstore-target-with-package-metadata.json rename to bin/typescript-fetch-petstore-with-npm-version.json diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.sh b/bin/typescript-fetch-petstore-with-npm-version.sh similarity index 88% rename from bin/typescript-fetch-petstore-target-with-package-metadata.sh rename to bin/typescript-fetch-petstore-with-npm-version.sh index 3c4978c8a80..fd9225f0e72 100755 --- a/bin/typescript-fetch-petstore-target-with-package-metadata.sh +++ b/bin/typescript-fetch-petstore-with-npm-version.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/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh index 6283285c736..50d56f34609 100755 --- a/bin/typescript-fetch-petstore.sh +++ b/bin/typescript-fetch-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/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/java-petstore-okhttp-gson.bat b/bin/windows/java-petstore-okhttp-gson.bat new file mode 100755 index 00000000000..e7c1dde982a --- /dev/null +++ b/bin/windows/java-petstore-okhttp-gson.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore.bat b/bin/windows/java-petstore.bat index 18544cbad36..02a81e1adbf 100755 --- a/bin/windows/java-petstore.bat +++ b/bin/windows/java-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java +set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java -DdateLibrary=joda,hideGenerationTimestamp=true java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rails-petstore-server.bat b/bin/windows/rails-petstore-server.bat new file mode 100644 index 00000000000..55677b55197 --- /dev/null +++ b/bin/windows/rails-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 +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l aspnet5 -o samples\server\petstore\rails5\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rails5-petstore-server.bat b/bin/windows/rails5-petstore-server.bat new file mode 100755 index 00000000000..a0316279784 --- /dev/null +++ b/bin/windows/rails5-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 +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l rails5 -o samples\server\petstore\rails5\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 90a14b16deb..92490778689 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.6 + 2.2.0-SNAPSHOT ../.. 4.0.0 @@ -100,4 +100,4 @@ - \ No newline at end of file + diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index 488148727b2..d9282c97ebf 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -48,6 +48,44 @@ mvn clean compile - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) +### Custom Generator + +Specifying a custom generator is a bit different. It doesn't support the classpath:/ syntax, but it does support the fully qualified name of the package. You can also specify your custom templates, which also get pulled in. Notice the dependency on a project, in the plugin scope. That would be your generator/template jar. + +```xml + + io.swagger + swagger-codegen-maven-plugin + ${swagger-codegen-maven-plugin-version} + + + + generate + + + src/main/resources/yaml/yamlfilename.yaml + + com.my.package.for.GeneratorLanguage + myTemplateDir + + ${project.build.directory}/generated-sources + ${default.package}.handler + ${default.package}.model + ${default.package}.handler + + + + + + + com.my.generator + customgenerator + 1.0-SNAPSHOT + + + +``` + ### Sample configuration -- Please see [an example configuration](examples) for using the plugin \ No newline at end of file +- Please see [an example configuration](examples) for using the plugin diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index b45e0d97874..0b6885bf048 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.6 + 2.2.0-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 79a100bba21..261d539e2e5 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -163,8 +163,6 @@ public class CodeGenMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { - Swagger swagger = new SwaggerParser().read(inputSpec); - //attempt to read from config file CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile); diff --git a/modules/swagger-codegen/.gitignore b/modules/swagger-codegen/.gitignore index d027396de4e..f4ccae271fa 100644 --- a/modules/swagger-codegen/.gitignore +++ b/modules/swagger-codegen/.gitignore @@ -1 +1,2 @@ /.settings/ +/test-output/ diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 9ea75ad3c88..8f7e98074de 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.6 + 2.2.0-SNAPSHOT ../.. 4.0.0 @@ -199,6 +199,9 @@ + + 1.2.1 + io.swagger @@ -279,6 +282,13 @@ test + + com.googlecode.java-diff-utils + diffutils + ${diffutils-version} + test + + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 1d92c923c5c..849651baa9d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -72,33 +72,35 @@ public abstract class AbstractGenerator { * @return String Full template file path */ public String getFullTemplateFile(CodegenConfig config, String templateFile) { - String library = config.getLibrary(); - if (library != null && !"".equals(library)) { - String libTemplateFile = config.templateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - templateFile; - - if (new File(libTemplateFile).exists()) { - return libTemplateFile; - } - - libTemplateFile = config.embeddedTemplateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - templateFile; - if (embeddedTemplateExists(libTemplateFile)) { - // Fall back to the template file embedded/packaged in the JAR file... - return libTemplateFile; - } - } String template = config.templateDir() + File.separator + templateFile; if (new File(template).exists()) { return template; } else { + String library = config.getLibrary(); + if (library != null && !"".equals(library)) { + String libTemplateFile = config.embeddedTemplateDir() + File.separator + + "libraries" + File.separator + library + File.separator + + templateFile; + if (embeddedTemplateExists(libTemplateFile)) { + // Fall back to the template file embedded/packaged in the JAR file... + return libTemplateFile; + } + } // Fall back to the template file embedded/packaged in the JAR file... return config.embeddedTemplateDir() + File.separator + templateFile; } } + public String readResourceContents(String resourceFilePath) { + StringBuilder sb = new StringBuilder(); + Scanner scanner = new Scanner(this.getClass().getResourceAsStream(getCPResourcePath(resourceFilePath)), "UTF-8"); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + sb.append(line).append('\n'); + } + return sb.toString(); + } + public boolean embeddedTemplateExists(String name) { return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java index 1087de5786d..172a057ea43 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java @@ -1,10 +1,10 @@ package io.swagger.codegen; -import io.swagger.codegen.auth.AuthMethod; - import java.util.HashMap; import java.util.Map; +import io.swagger.codegen.auth.AuthMethod; + public class ClientOpts { protected String uri; protected String target; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 3dc90472247..72a2e50d149 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -184,4 +184,5 @@ public interface CodegenConfig { String getHttpUserAgent(); + String getCommonTemplateDir(); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index b4b414bb00d..52af81d0726 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -105,4 +105,14 @@ public class CodegenConstants { public static final String SUPPORTS_ES6 = "supportsES6"; public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6."; + + public static final String EXCLUDE_TESTS = "excludeTests"; + public static final String EXCLUDE_TESTS_DESC = "Specifies that no tests are to be generated."; + + public static final String GENERATE_API_TESTS = "generateApiTests"; + public static final String GENERATE_API_TESTS_DESC = "Specifies that api tests are to be generated."; + + public static final String GENERATE_MODEL_TESTS = "generateModelTests"; + public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated."; + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index ccea2ee070e..c11f444437b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -1,7 +1,13 @@ package io.swagger.codegen; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + import io.swagger.models.ExternalDocs; -import java.util.*; + public class CodegenModel { public String parent, parentSchema; @@ -19,6 +25,8 @@ public class CodegenModel { public List vars = new ArrayList(); public List requiredVars = new ArrayList(); // a list of required properties public List optionalVars = new ArrayList(); // a list of optional properties + public List readOnlyVars = new ArrayList(); // a list of read-only properties + public List readWriteVars = new ArrayList(); // a list of properties for read, write public List allVars; public Map allowableValues; @@ -27,11 +35,14 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired; public ExternalDocs externalDocs; public Map vendorExtensions; + //The type of the value from additional properties. Used in map like objects. + public String additionalPropertiesType; + { // By default these are the same collections. Where the code generator supports inheritance, composed models // store the complete closure of owned and inherited properties in allVars and allMandatory. diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 48858a0d504..9dfe0d45c88 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -7,13 +7,16 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Arrays; public class CodegenOperation { public final List responseHeaders = new ArrayList(); public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, isMultipart, hasMore = Boolean.TRUE, - isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; + isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, + isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, + isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; public List> consumes, produces; @@ -88,6 +91,81 @@ public class CodegenOperation { return nonempty(formParams); } + /** + * Check if act as Restful index method + * + * @return true if act as Restful index method, false otherwise + */ + public boolean isRestfulIndex() { + return "GET".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful show method + * + * @return true if act as Restful show method, false otherwise + */ + public boolean isRestfulShow() { + return "GET".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful create method + * + * @return true if act as Restful create method, false otherwise + */ + public boolean isRestfulCreate() { + return "POST".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful update method + * + * @return true if act as Restful update method, false otherwise + */ + public boolean isRestfulUpdate() { + return Arrays.asList("PUT", "PATCH").contains(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful destroy method + * + * @return true if act as Restful destroy method, false otherwise + */ + public boolean isRestfulDestroy() { + return "DELETE".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if Restful-style + * + * @return true if Restful-style, false otherwise + */ + public boolean isRestful() { + return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy(); + } + + /** + * Get the substring except baseName from path + * + * @return the substring + */ + private String pathWithoutBaseName() { + return baseName != null ? path.replace("/" + baseName.toLowerCase(), "") : path; + } + + /** + * Check if the path match format /xxx/:id + * + * @return true if path act as member + */ + private boolean isMemberPath() { + if (pathParams.size() != 1) return false; + + String id = pathParams.get(0).baseName; + return ("/{" + id + "}").equals(pathWithoutBaseName()); + } + @Override public String toString() { return String.format("%s(%s)", baseName, path); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 5d71a347df0..8304849a14c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2,25 +2,76 @@ package io.swagger.codegen; import com.google.common.base.Function; import com.google.common.collect.Lists; -import io.swagger.codegen.examples.ExampleGenerator; -import io.swagger.models.*; -import io.swagger.models.auth.*; -import io.swagger.models.parameters.*; -import io.swagger.models.properties.*; -import io.swagger.models.properties.PropertyBuilder.PropertyId; -import io.swagger.util.Json; + import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.Nullable; + +import io.swagger.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.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 { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -43,6 +94,7 @@ public class DefaultCodegen { protected Map modelDocTemplateFiles = new HashMap(); protected String templateDir; protected String embeddedTemplateDir; + protected String commonTemplateDir = "_common"; protected Map additionalProperties = new HashMap(); protected Map vendorExtensions = new HashMap(); protected List supportingFiles = new ArrayList(); @@ -390,6 +442,14 @@ public class DefaultCodegen { } } + public String getCommonTemplateDir() { + return this.commonTemplateDir; + } + + public void setCommonTemplateDir(String commonTemplateDir) { + this.commonTemplateDir = commonTemplateDir; + } + public Map apiDocTemplateFiles() { return apiDocTemplateFiles; } @@ -732,6 +792,12 @@ public class DefaultCodegen { importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); + // we've used the .swagger-codegen-ignore approach as + // suppportingFiles can be cleared by code generator that extends + // the default codegen, leaving the commented code below for + // future reference + //supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants @@ -1207,8 +1273,7 @@ public class DefaultCodegen { m.dataType = getSwaggerType(p); } if (impl.getAdditionalProperties() != null) { - MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); - addParentContainer(m, name, mapProperty); + addAdditionPropertiesToCodeGenModel(m, impl); } addVars(m, impl.getProperties(), impl.getRequired()); } @@ -1221,8 +1286,12 @@ public class DefaultCodegen { return m; } - protected void addProperties(Map properties, List required, Model model, - Map allDefinitions) { + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { + MapProperty mapProperty = new MapProperty(swaggerModel.getAdditionalProperties()); + addParentContainer(codegenModel, codegenModel.name, mapProperty); + } + + protected void addProperties(Map properties, List required, Model model, Map allDefinitions) { if (model instanceof ModelImpl) { ModelImpl mi = (ModelImpl) model; @@ -1847,6 +1916,14 @@ public class DefaultCodegen { } op.externalDocs = operation.getExternalDocs(); + // set Restful Flag + op.isRestfulShow = op.isRestfulShow(); + op.isRestfulIndex = op.isRestfulIndex(); + op.isRestfulCreate = op.isRestfulCreate(); + op.isRestfulUpdate = op.isRestfulUpdate(); + op.isRestfulDestroy = op.isRestfulDestroy(); + op.isRestful = op.isRestful(); + return op; } @@ -1887,7 +1964,7 @@ public class DefaultCodegen { } } r.dataType = cm.datatype; - r.isBinary = cm.datatype.toLowerCase().startsWith("byte"); + r.isBinary = isDataTypeBinary(cm.datatype); if (cm.isContainer != null) { r.simpleType = false; r.containerType = cm.containerType; @@ -2056,7 +2133,7 @@ public class DefaultCodegen { p.baseType = cp.baseType; p.dataType = cp.datatype; p.isPrimitiveType = cp.isPrimitiveType; - p.isBinary = cp.datatype.toLowerCase().startsWith("byte"); + p.isBinary = isDataTypeBinary(cp.datatype); } // set boolean flag (e.g. isString) @@ -2153,7 +2230,7 @@ public class DefaultCodegen { p.isCookieParam = true; } else if (param instanceof BodyParameter) { p.isBodyParam = true; - p.isBinary = p.dataType.toLowerCase().startsWith("byte"); + p.isBinary = isDataTypeBinary(p.dataType); } else if (param instanceof FormParameter) { if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { p.isFile = true; @@ -2169,6 +2246,10 @@ public class DefaultCodegen { return p; } + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("byte"); + } + /** * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects * @@ -2452,7 +2533,7 @@ public class DefaultCodegen { } } - private void addImport(CodegenModel m, String type) { + protected void addImport(CodegenModel m, String type) { if (type != null && needToImport(type)) { m.imports.add(type); } @@ -2465,6 +2546,7 @@ public class DefaultCodegen { 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; @@ -2503,6 +2585,7 @@ public class DefaultCodegen { } else { final CodegenProperty cp = fromProperty(key, prop); cp.required = mandatory.contains(key) ? true : null; + m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required); if (cp.isEnum) { // FIXME: if supporting inheritance, when called a second time for allProperties it is possible for // m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not. @@ -2525,11 +2608,19 @@ public class DefaultCodegen { addImport(m, cp.complexType); vars.add(cp); - if (Boolean.TRUE.equals(cp.required)) { // if required, add to the list "requiredVars" + // if required, add to the list "requiredVars" + if (Boolean.TRUE.equals(cp.required)) { m.requiredVars.add(cp); } else { // else add to the list "optionalVars" for optional property m.optionalVars.add(cp); } + + // if readonly, add to readOnlyVars (list of properties) + if (Boolean.TRUE.equals(cp.isReadOnly)) { + m.readOnlyVars.add(cp); + } else { // else add to readWriteVars (list of properties) + m.readWriteVars.add(cp); + } } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 8be354df1ee..6a489e45e52 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -2,6 +2,7 @@ package io.swagger.codegen; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; +import io.swagger.codegen.ignore.CodegenIgnoreProcessor; import io.swagger.models.*; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; @@ -24,6 +25,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { protected CodegenConfig config; protected ClientOptInput opts; protected Swagger swagger; + protected CodegenIgnoreProcessor ignoreProcessor; @Override public Generator opts(ClientOptInput opts) { @@ -31,8 +33,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { this.swagger = opts.getSwagger(); this.config = opts.getConfig(); + this.config.additionalProperties().putAll(opts.getOpts().getProperties()); + ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir()); + return this; } @@ -41,6 +46,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Boolean generateApis = null; Boolean generateModels = null; Boolean generateSupportingFiles = null; + Boolean generateApiTests = null; + Boolean generateApiDocumentation = null; + Boolean generateModelTests = null; + Boolean generateModelDocumentation = null; Set modelsToGenerate = null; Set apisToGenerate = null; @@ -68,6 +77,18 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); } } + if(System.getProperty("modelTests") != null) { + generateModelTests = Boolean.valueOf(System.getProperty("modelTests")); + } + if(System.getProperty("modelDocs") != null) { + generateModelDocumentation = Boolean.valueOf(System.getProperty("modelDocs")); + } + if(System.getProperty("apiTests") != null) { + generateApiTests = Boolean.valueOf(System.getProperty("apiTests")); + } + if(System.getProperty("apiDocs") != null) { + generateApiDocumentation = Boolean.valueOf(System.getProperty("apiDocs")); + } if(generateApis == null && generateModels == null && generateSupportingFiles == null) { // no specifics are set, generate everything @@ -85,6 +106,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } + // model/api tests and documentation options rely on parent generate options (api or model) and no other options. + // They default to true in all scenarios and can only be marked false explicitly + if (generateModelTests == null) { + generateModelTests = true; + } + if (generateModelDocumentation == null) { + generateModelDocumentation = true; + } + if (generateApiTests == null) { + generateApiTests = true; + } + if (generateApiDocumentation == null) { + generateApiDocumentation = true; + } + + // Additional properties added for tests to exclude references in project related files + config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests); + config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); + if(Boolean.FALSE.equals(generateApiTests) && Boolean.FALSE.equals(generateModelTests)) { + config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE); + } + if (swagger == null || config == null) { throw new RuntimeException("missing swagger input or config!"); } @@ -159,7 +202,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { String basePath = hostBuilder.toString(); String basePathWithoutHost = swagger.getBasePath(); - // resolve inline models InlineModelResolver inlineModelResolver = new InlineModelResolver(); inlineModelResolver.flatten(swagger); @@ -267,66 +309,46 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { LOGGER.info("Skipped overwriting " + filename); continue; } - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - writeToFile(filename, tmpl.execute(models)); - files.add(new File(filename)); + + File written = processTemplateToFile(models, templateName, filename); + if(written != null) { + files.add(written); + } } - // to generate model test files - for (String templateName : config.modelTestTemplateFiles().keySet()) { - String suffix = config.modelTestTemplateFiles().get(templateName); - String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; - // do not overwrite test file that already exists - if (new File(filename).exists()) { - LOGGER.info("File exists. Skipped overwriting " + filename); - continue; + if(generateModelTests) { + // to generate model test files + for (String templateName : config.modelTestTemplateFiles().keySet()) { + String suffix = config.modelTestTemplateFiles().get(templateName); + String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); + continue; + } + + File written = processTemplateToFile(models, templateName, filename); + if (written != null) { + files.add(written); + } } - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - writeToFile(filename, tmpl.execute(models)); - files.add(new File(filename)); } - // to generate model documentation files - for (String templateName : config.modelDocTemplateFiles().keySet()) { - String suffix = config.modelDocTemplateFiles().get(templateName); - String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix; - if (!config.shouldOverwrite(filename)) { - LOGGER.info("Skipped overwriting " + filename); - continue; + if(generateModelDocumentation) { + // to generate model documentation files + for (String templateName : config.modelDocTemplateFiles().keySet()) { + String suffix = config.modelDocTemplateFiles().get(templateName); + String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix; + if (!config.shouldOverwrite(filename)) { + LOGGER.info("Skipped overwriting " + filename); + continue; + } + + File written = processTemplateToFile(models, templateName, filename); + if (written != null) { + files.add(written); + } } - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - writeToFile(filename, tmpl.execute(models)); - files.add(new File(filename)); } } catch (Exception e) { throw new RuntimeException("Could not generate model '" + name + "'", e); @@ -401,68 +423,44 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { continue; } - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - - writeToFile(filename, tmpl.execute(operation)); - files.add(new File(filename)); + File written = processTemplateToFile(operation, templateName, filename); + if(written != null) { + files.add(written); + } } - // to generate api test files - for (String templateName : config.apiTestTemplateFiles().keySet()) { - String filename = config.apiTestFilename(templateName, tag); - // do not overwrite test file that already exists - if (new File(filename).exists()) { - LOGGER.info("File exists. Skipped overwriting " + filename); - continue; - } - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); + if(generateApiTests) { + // to generate api test files + for (String templateName : config.apiTestTemplateFiles().keySet()) { + String filename = config.apiTestFilename(templateName, tag); + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); + continue; + } - writeToFile(filename, tmpl.execute(operation)); - files.add(new File(filename)); + File written = processTemplateToFile(operation, templateName, filename); + if (written != null) { + files.add(written); + } + } } - // to generate api documentation files - for (String templateName : config.apiDocTemplateFiles().keySet()) { - String filename = config.apiDocFilename(templateName, tag); - if (!config.shouldOverwrite(filename) && new File(filename).exists()) { - LOGGER.info("Skipped overwriting " + filename); - continue; + + if(generateApiDocumentation) { + // to generate api documentation files + for (String templateName : config.apiDocTemplateFiles().keySet()) { + String filename = config.apiDocFilename(templateName, tag); + if (!config.shouldOverwrite(filename) && new File(filename).exists()) { + LOGGER.info("Skipped overwriting " + filename); + continue; + } + + File written = processTemplateToFile(operation, templateName, filename); + if (written != null) { + files.add(written); + } } - - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - - writeToFile(filename, tmpl.execute(operation)); - files.add(new File(filename)); } } catch (Exception e) { @@ -488,6 +486,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } bundle.put("swagger", this.swagger); bundle.put("basePath", basePath); + bundle.put("basePathWithoutHost",basePathWithoutHost); bundle.put("scheme", scheme); bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); @@ -531,9 +530,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { LOGGER.info("Skipped overwriting " + outputFilename); continue; } - - String templateFile = getFullTemplateFile(config, support.templateFile); - + String templateFile; + if( support instanceof GlobalSupportingFile) { + templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile; + } else { + templateFile = getFullTemplateFile(config, support.templateFile); + } boolean shouldGenerate = true; if(supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) { if(supportingFilesToGenerate.contains(support.destinationFilename)) { @@ -544,53 +546,108 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } if(shouldGenerate) { - if (templateFile.endsWith("mustache")) { - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); + if(ignoreProcessor.allowsFile(new File(outputFilename))) { + if (templateFile.endsWith("mustache")) { + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); - writeToFile(outputFilename, tmpl.execute(bundle)); - files.add(new File(outputFilename)); - } else { - InputStream in = null; - - try { - in = new FileInputStream(templateFile); - } catch (Exception e) { - // continue - } - if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); - } - File outputFile = new File(outputFilename); - OutputStream out = new FileOutputStream(outputFile, false); - if (in != null) { - LOGGER.info("writing file " + outputFile); - IOUtils.copy(in, out); + writeToFile(outputFilename, tmpl.execute(bundle)); + files.add(new File(outputFilename)); } else { - if (in == null) { - LOGGER.error("can't open " + templateFile + " for input"); + InputStream in = null; + + try { + in = new FileInputStream(templateFile); + } catch (Exception e) { + // continue } + if (in == null) { + in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); + } + File outputFile = new File(outputFilename); + OutputStream out = new FileOutputStream(outputFile, false); + if (in != null) { + LOGGER.info("writing file " + outputFile); + IOUtils.copy(in, out); + } else { + if (in == null) { + LOGGER.error("can't open " + templateFile + " for input"); + } + } + files.add(outputFile); } - files.add(outputFile); + } else { + LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); } } } catch (Exception e) { throw new RuntimeException("Could not generate supporting file '" + support + "'", e); } } + + // Consider .swagger-codegen-ignore a supporting file + // Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator + final String swaggerCodegenIgnore = ".swagger-codegen-ignore"; + String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore; + File ignoreFile = new File(ignoreFileNameTarget); + if(!ignoreFile.exists()) { + String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore; + String ignoreFileContents = readResourceContents(ignoreFileNameSource); + try { + writeToFile(ignoreFileNameTarget, ignoreFileContents); + } catch (IOException e) { + throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e); + } + files.add(ignoreFile); + } + + // Add default LICENSE (Apache-2.0) for all generators + final String apache2License = "LICENSE"; + String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License; + File licenseFile = new File(licenseFileNameTarget); + String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + apache2License; + String licenseFileContents = readResourceContents(licenseFileNameSource); + try { + writeToFile(licenseFileNameTarget, licenseFileContents); + } catch (IOException e) { + throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e); + } + files.add(licenseFile); } config.processSwagger(swagger); return files; } + private File processTemplateToFile(Map templateData, String templateName, String outputFilename) throws IOException { + if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) { + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(templateData)); + return new File(outputFilename); + } + + LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); + return null; + } + private static void processMimeTypes(List mimeTypeList, Map operation, String source) { if (mimeTypeList != null && mimeTypeList.size() > 0) { List> c = new ArrayList>(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/GlobalSupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/GlobalSupportingFile.java new file mode 100644 index 00000000000..ee7a1dc659b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/GlobalSupportingFile.java @@ -0,0 +1,12 @@ +package io.swagger.codegen; + +public class GlobalSupportingFile extends SupportingFile { + + GlobalSupportingFile(String templateFile, String folder, String destinationFilename) { + super(templateFile, folder, destinationFilename); + } + + GlobalSupportingFile(String templateFile, String destinationFilename) { + super(templateFile, destinationFilename); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index 2f8dc6e3575..e82f92b5024 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -50,7 +50,7 @@ public class InlineModelResolver { if (obj.getType() == null || "object".equals(obj.getType())) { if (obj.getProperties() != null && obj.getProperties().size() > 0) { flattenProperties(obj.getProperties(), pathname); - String modelName = uniqueName(bp.getName()); + String modelName = resolveModelName( obj.getTitle(), bp.getName()); bp.setSchema(new RefModel(modelName)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); @@ -65,7 +65,7 @@ public class InlineModelResolver { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); - String modelName = uniqueName(bp.getName()); + String modelName = resolveModelName( op.getTitle(), bp.getName()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -91,7 +91,7 @@ public class InlineModelResolver { if (property instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) property; if (op.getProperties() != null && op.getProperties().size() > 0) { - String modelName = uniqueName("inline_response_" + key); + String modelName = resolveModelName( op.getTitle(),"inline_response_" + key); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { @@ -108,18 +108,18 @@ public class InlineModelResolver { if(inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = uniqueName("inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - ap.setItems(new RefProperty(existing)); - } else { + 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) { + ap.setItems(new RefProperty(existing)); + } else { ap.setItems(new RefProperty(modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); - } + } } } } else if (property instanceof MapProperty) { @@ -129,18 +129,18 @@ public class InlineModelResolver { if(innerProperty instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) innerProperty; if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = uniqueName("inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - mp.setAdditionalProperties(new RefProperty(existing)); - } else { - mp.setAdditionalProperties(new RefProperty(modelName)); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } + flattenProperties(op.getProperties(), pathname); + String modelName = resolveModelName( op.getTitle(),"inline_response_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + mp.setAdditionalProperties(new RefProperty(existing)); + } else { + mp.setAdditionalProperties(new RefProperty(modelName)); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } } } } @@ -184,6 +184,15 @@ public class InlineModelResolver { } } + 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; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java index e5fb6a27da6..74bee83ef24 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -5,6 +5,10 @@ public class SupportingFile { public String folder; public String destinationFilename; + public SupportingFile(String templateFile, String destinationFilename) { + this(templateFile, "", destinationFilename); + } + public SupportingFile(String templateFile, String folder, String destinationFilename) { this.templateFile = templateFile; this.folder = folder; @@ -44,4 +48,6 @@ public class SupportingFile { result = 31 * result + (destinationFilename != null ? destinationFilename.hashCode() : 0); return result; } -} \ No newline at end of file +} + + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java new file mode 100644 index 00000000000..fb25ac82b28 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java @@ -0,0 +1,134 @@ +package io.swagger.codegen.ignore; + +import com.google.common.collect.ImmutableList; +import io.swagger.codegen.ignore.rules.DirectoryRule; +import io.swagger.codegen.ignore.rules.Rule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class CodegenIgnoreProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class); + private final String outputPath; + private List exclusionRules = new ArrayList<>(); + private List inclusionRules = new ArrayList<>(); + + public CodegenIgnoreProcessor(String outputPath) { + this.outputPath = outputPath; + final File directory = new File(outputPath); + if(directory.exists() && directory.isDirectory()){ + final File codegenIgnore = new File(directory, ".swagger-codegen-ignore"); + if(codegenIgnore.exists() && codegenIgnore.isFile()){ + try { + loadCodegenRules(codegenIgnore); + } catch (IOException e) { + LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage()); + } + } else { + // log info message + LOGGER.info("No .swagger-codegen-ignore file found."); + } + } + } + + void loadCodegenRules(File codegenIgnore) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) { + String line; + + // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore + // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt + while ((line = reader.readLine()) != null) { + if( + //: A blank line matches no files, so it can serve as a separator for readability. + line.length() == 0 + ) continue; + + Rule rule = Rule.create(line); + + // rule could be null here if it's a COMMENT, for example + if(rule != null) { + if (Boolean.TRUE.equals(rule.getNegated())) { + inclusionRules.add(rule); + } else { + exclusionRules.add(rule); + } + } + } + } + } + + public boolean allowsFile(File targetFile) { + File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath()); + Boolean directoryExcluded = false; + Boolean exclude = false; + if(exclusionRules.size() == 0 && inclusionRules.size() == 0) { + return true; + } + + // NOTE: We *must* process all exclusion rules + for (int i = 0; i < exclusionRules.size(); i++) { + Rule current = exclusionRules.get(i); + Rule.Operation op = current.evaluate(file.getPath()); + + switch (op){ + case EXCLUDE: + exclude = true; + + // Include rule can't override rules that exclude a file by some parent directory. + if(current instanceof DirectoryRule) { + directoryExcluded = true; + } + break; + case INCLUDE: + // This won't happen here. + break; + case NOOP: + break; + case EXCLUDE_AND_TERMINATE: + i = exclusionRules.size(); + break; + } + } + + if(exclude) { + // Only need to process inclusion rules if we've been excluded + for (int i = 0; exclude && i < inclusionRules.size(); i++) { + Rule current = inclusionRules.get(i); + Rule.Operation op = current.evaluate(file.getPath()); + + // At this point exclude=true means the file should be ignored. + // op == INCLUDE means we have to flip that flag. + if(op.equals(Rule.Operation.INCLUDE)) { + if(current instanceof DirectoryRule && directoryExcluded) { + // e.g + // baz/ + // !foo/bar/baz/ + // NOTE: Possibly surprising side effect: + // foo/bar/baz/ + // !bar/ + exclude = false; + } else if (!directoryExcluded) { + // e.g. + // **/*.log + // !ISSUE_1234.log + exclude = false; + } + } + } + } + + return Boolean.FALSE.equals(exclude); + } + + public List getInclusionRules() { + return ImmutableList.copyOf(inclusionRules); + } + + public List getExclusionRules() { + return ImmutableList.copyOf(exclusionRules); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java new file mode 100644 index 00000000000..235d34d3f96 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java @@ -0,0 +1,27 @@ +package io.swagger.codegen.ignore.rules; + +import java.nio.file.*; +import java.util.List; + +public class DirectoryRule extends FileRule { + + private PathMatcher directoryMatcher = null; + private PathMatcher contentsMatcher = null; + + DirectoryRule(List syntax, String definition) { + super(syntax, definition); + String pattern = this.getPattern(); + StringBuilder sb = new StringBuilder(); + sb.append("glob:"); + sb.append(pattern); + if(!pattern.endsWith("/")) sb.append("/"); + directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); + sb.append("**"); + contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); + } + + @Override + public Boolean matches(String relativePath) { + return contentsMatcher.matches(FileSystems.getDefault().getPath(relativePath)) || directoryMatcher.matches(FileSystems.getDefault().getPath(relativePath)); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java new file mode 100644 index 00000000000..f942cb222ce --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java @@ -0,0 +1,20 @@ +package io.swagger.codegen.ignore.rules; + +import java.util.List; + +/** + * An ignore rule which matches everything. + */ +public class EverythingRule extends Rule { + EverythingRule(List syntax, String definition) { + super(syntax, definition); + } + + @Override + public Boolean matches(String relativePath) { + return true; + } + + @Override + protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java new file mode 100644 index 00000000000..a97513dc1e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java @@ -0,0 +1,20 @@ +package io.swagger.codegen.ignore.rules; + +import java.nio.file.FileSystems; +import java.nio.file.PathMatcher; +import java.util.List; + +public class FileRule extends Rule { + + private PathMatcher matcher = null; + + FileRule(List syntax, String definition) { + super(syntax, definition); + matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern()); + } + + @Override + public Boolean matches(String relativePath) { + return matcher.matches(FileSystems.getDefault().getPath(relativePath)); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java new file mode 100644 index 00000000000..2d3fbdd2994 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java @@ -0,0 +1,141 @@ +package io.swagger.codegen.ignore.rules; + +import java.util.ArrayList; +import java.util.List; + +public class IgnoreLineParser { + enum Token { + MATCH_ALL("**"), + MATCH_ANY("*"), + ESCAPED_EXCLAMATION("\\!"), + ESCAPED_SPACE("\\ "), + PATH_DELIM("/"), + NEGATE("!"), + TEXT(null), + DIRECTORY_MARKER("/"), + ROOTED_MARKER("/"), + COMMENT(null); + + private String pattern; + + Token(String pattern) { + this.pattern = pattern; + } + + public String getPattern() { + return pattern; + } + } + + // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore + // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt + static List parse(String text) throws ParserException { + List parts = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + String current = null; + String next = null; + + char[] characters = text.toCharArray(); + for (int i = 0, totalLength = characters.length; i < totalLength; i++) { + char character = characters[i]; + current = String.valueOf(character); + next = i < totalLength - 1 ? String.valueOf(characters[i + 1]) : null; + + if (i == 0) { + if ("#".equals(current)) { + //: A line starting with # serves as a comment. + parts.add(new Part(Token.COMMENT, text)); + i = totalLength; // rather than early return + continue; + } else if ("!".equals(current)) { + if (i == totalLength - 1) { + throw new ParserException("Negation with no negated pattern."); + } else { + parts.add(new Part(Token.NEGATE)); + continue; + } + } else if ("\\".equals(current) && "#".equals(next)) { + //: Put a backslash ("`\`") in front of the first hash for patterns + //: that begin with a hash. + // NOTE: Just push forward and drop the escape character. Falls through to TEXT token. + current = next; + next = null; + i++; + } + } + + if (Token.MATCH_ANY.pattern.equals(current)) { + + if (Token.MATCH_ANY.pattern.equals(next)) { + // peek ahead for invalid pattern. Slightly inefficient, but acceptable. + if ((i+2 < totalLength - 1) && + String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) { + // It doesn't matter where we are in the pattern, *** is invalid. + throw new ParserException("The pattern *** is invalid."); + } + + parts.add(new Part(Token.MATCH_ALL)); + i++; + continue; + } else { + + if (sb.length() > 0) { + // A MATCH_ANY may commonly follow a filename or some other character. Dump that to results before the MATCH_ANY. + parts.add(new Part(Token.TEXT, sb.toString())); + sb.delete(0, sb.length()); + } + + parts.add(new Part(Token.MATCH_ANY)); + continue; + } + } + + if (i == 0 && Token.ROOTED_MARKER.pattern.equals(current)) { + parts.add(new Part(Token.ROOTED_MARKER)); + continue; + } + + if ("\\".equals(current) && " ".equals(next)) { + parts.add(new Part(Token.ESCAPED_SPACE)); + i++; + continue; + } else if ("\\".equals(current) && "!".equals(next)) { + parts.add(new Part(Token.ESCAPED_EXCLAMATION)); + i++; + continue; + } + + if (Token.PATH_DELIM.pattern.equals(current)) { + if (i != totalLength - 1) { + if (sb.length() > 0) { + parts.add(new Part(Token.TEXT, sb.toString())); + sb.delete(0, sb.length()); + } + + parts.add(new Part(Token.PATH_DELIM)); + if(Token.PATH_DELIM.pattern.equals(next)) { + // ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in // + i++; + } + continue; + } else if (i == totalLength - 1) { + parts.add(new Part(Token.TEXT, sb.toString())); + sb.delete(0, sb.length()); + + parts.add(new Part(Token.DIRECTORY_MARKER)); + continue; + } + } + + sb.append(current); + } + + if (sb.length() > 0) { + // NOTE: All spaces escaped spaces are a special token, ESCAPED_SPACE + //: Trailing spaces are ignored unless they are quoted with backslash ("`\`") + parts.add(new Part(Token.TEXT, sb.toString().trim())); + } + + return parts; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/InvalidRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/InvalidRule.java new file mode 100644 index 00000000000..46524f4795b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/InvalidRule.java @@ -0,0 +1,26 @@ +package io.swagger.codegen.ignore.rules; + +import java.util.List; + +public class InvalidRule extends Rule { + private final String reason; + + InvalidRule(List syntax, String definition, String reason) { + super(syntax, definition); + this.reason = reason; + } + + @Override + public Boolean matches(String relativePath) { + return null; + } + + @Override + public Operation evaluate(String relativePath) { + return Operation.NOOP; + } + + public String getReason() { + return reason; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java new file mode 100644 index 00000000000..03e02d8fd70 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java @@ -0,0 +1,15 @@ +package io.swagger.codegen.ignore.rules; + +public class ParserException extends Exception { + /** + * Constructs a new exception with the specified detail message. The + * cause is not initialized, and may subsequently be initialized by + * a call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public ParserException(String message) { + super(message); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java new file mode 100644 index 00000000000..71379922175 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java @@ -0,0 +1,24 @@ +package io.swagger.codegen.ignore.rules; + +class Part { + private final IgnoreLineParser.Token token; + private final String value; + + public Part(IgnoreLineParser.Token token, String value) { + this.token = token; + this.value = value; + } + + public Part(IgnoreLineParser.Token token) { + this.token = token; + this.value = token.getPattern(); + } + + public IgnoreLineParser.Token getToken() { + return token; + } + + public String getValue() { + return value; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java new file mode 100644 index 00000000000..6c445b6299a --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java @@ -0,0 +1,58 @@ +package io.swagger.codegen.ignore.rules; + +import java.util.List; +import java.util.regex.Pattern; + +/** + * A special case rule which matches files only if they're located + * in the same directory as the .swagger-codegen-ignore file. + */ +public class RootedFileRule extends Rule { + private String definedFilename = null; + private String definedExtension = null; + + RootedFileRule(List syntax, String definition) { + super(syntax, definition); + + int separatorIndex = definition.lastIndexOf("."); + definedFilename = getFilenamePart(definition, separatorIndex); + definedExtension = getExtensionPart(definition, separatorIndex); + } + + private String getFilenamePart(final String input, int stopIndex){ + return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length()); + } + + private String getExtensionPart(final String input, int stopIndex) { + return input.substring(stopIndex > 0 ? stopIndex+1: input.length(), input.length()); + } + + @Override + public Boolean matches(String relativePath) { + // NOTE: Windows-style separator isn't supported, so File.pathSeparator would be incorrect here. + // NOTE: lastIndexOf rather than contains because /file.txt is acceptable while path/file.txt is not. + // relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore. + boolean isSingleFile = relativePath.lastIndexOf("/") <= 0; + + if(isSingleFile) { + int separatorIndex = relativePath.lastIndexOf("."); + final String filename = getFilenamePart(relativePath, separatorIndex); + final String extension = getExtensionPart(relativePath, separatorIndex); + boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern()); + + if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) { + // TODO: Evaluate any other escape requirements here. + Pattern regex = Pattern.compile( + definedFilename + .replaceAll(Pattern.quote("."), "\\\\Q.\\\\E") + .replaceAll(Pattern.quote("*"), ".*?") // non-greedy match on 0+ any character + ); + return regex.matcher(filename).matches(); + } + + return extensionMatches && definedFilename.equals(filename); + } + + return false; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java new file mode 100644 index 00000000000..8d199cba763 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java @@ -0,0 +1,175 @@ +package io.swagger.codegen.ignore.rules; + +import java.util.List; + +public abstract class Rule { + + public enum Operation {EXCLUDE, INCLUDE, NOOP, EXCLUDE_AND_TERMINATE} + + // The original rule + private final String definition; + + private final List syntax; + + Rule(List syntax, String definition) { + this.syntax = syntax; + this.definition = definition; + } + + public abstract Boolean matches(String relativePath); + + public String getDefinition() { + return this.definition; + } + + protected String getPattern() { + if(syntax == null) return this.definition; + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < syntax.size(); i++) { + Part current = syntax.get(i); + + switch(current.getToken()){ + case MATCH_ALL: + case MATCH_ANY: + case ESCAPED_EXCLAMATION: + case ESCAPED_SPACE: + case PATH_DELIM: + case TEXT: + case DIRECTORY_MARKER: + sb.append(current.getValue()); + break; + case NEGATE: + case ROOTED_MARKER: + case COMMENT: + break; + } + } + return sb.toString(); + } + + /** + * Whether or not the rule should be negated. !foo means foo should be removed from previous matches. + * Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root. + *

+ * NOTE: It is not possible to re-include a file if a parent directory of that file is excluded. + */ + public Boolean getNegated() { + return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE; + } + + public Operation evaluate(String relativePath) { + if (Boolean.TRUE.equals(matches(relativePath))) { + if(Boolean.TRUE.equals(this.getNegated())) { + return this.getIncludeOperation(); + } + return this.getExcludeOperation(); + } + return Operation.NOOP; + } + + protected Operation getIncludeOperation(){ return Operation.INCLUDE; } + protected Operation getExcludeOperation(){ return Operation.EXCLUDE; } + + public static Rule create(String definition) { + // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore + // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt + Rule rule = null; + if (definition.equals(".")) { + return new InvalidRule(null, definition, "Pattern '.' is invalid."); + } else if (definition.equals("!.")) { + return new InvalidRule(null, definition, "Pattern '!.' is invalid."); + } else if (definition.startsWith("..")) { + return new InvalidRule(null, definition, "Pattern '..' is invalid."); + } + + try { + List result = IgnoreLineParser.parse(definition); + + Boolean directoryOnly = null; + if (result.size() == 0) { + return rule; + } else if (result.size() == 1) { + // single-character filename only + Part part = result.get(0); + if (IgnoreLineParser.Token.MATCH_ANY.equals(part.getToken())) { + rule = new RootedFileRule(result, definition); + } else { + rule = new FileRule(result, definition); + } + } else { + IgnoreLineParser.Token head = result.get(0).getToken(); + + //: An optional prefix "`!`" which negates the pattern; any + //: matching file excluded by a previous pattern will become + //: included again. It is not possible to re-include a file if a parent + //: directory of that file is excluded. Git doesn't list excluded + //: directories for performance reasons, so any patterns on contained + //: files have no effect, no matter where they are defined. + //: Put a backslash ("`\`") in front of the first "`!`" for patterns + //: that begin with a literal "`!`", for example, "`\!important!.txt`". + // see this.getNegated(); + + //: If the pattern ends with a slash, it is removed for the + //: purpose of the following description, but it would only find + //: a match with a directory. In other words, `foo/` will match a + //: directory `foo` and paths underneath it, but will not match a + //: regular file or a symbolic link `foo` (this is consistent + //: with the way how pathspec works in general in Git). + directoryOnly = IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result.get(result.size() - 1).getToken()); + + if (directoryOnly) { + rule = new DirectoryRule(result, definition); + } else if (IgnoreLineParser.Token.PATH_DELIM.equals(head)) { + //: A leading slash matches the beginning of the pathname. + //: For example, "/{asterisk}.c" matches "cat-file.c" but not + //: "mozilla-sha1/sha1.c". + rule = new RootedFileRule(result, definition); + } else { + // case 1 + //: If the pattern does not contain a slash '/', Git treats it as + //: a shell glob pattern and checks for a match against the + //: pathname relative to the location of the `.gitignore` file + //: (relative to the toplevel of the work tree if not from a + //: `.gitignore` file). + + // case 2 + //: Otherwise, Git treats the pattern as a shell glob suitable + //: for consumption by fnmatch(3) with the FNM_PATHNAME flag: + //: wildcards in the pattern will not match a / in the pathname. + //: For example, "Documentation/{asterisk}.html" matches + //: "Documentation/git.html" but not "Documentation/ppc/ppc.html" + //: or "tools/perf/Documentation/perf.html". + + + // case 3 + //: Two consecutive asterisks ("`**`") in patterns matched against + //: full pathname may have special meaning: + //: + //: - A leading "`**`" followed by a slash means match in all + //: directories. For example, "`**/foo`" matches file or directory + //: "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`" + //: matches file or directory "`bar`" anywhere that is directly + //: under directory "`foo`". + //: + //: - A trailing "`/**`" matches everything inside. For example, + //: "`abc/**`" matches all files inside directory "`abc`", relative + //: to the location of the `.gitignore` file, with infinite depth. + //: + //: - A slash followed by two consecutive asterisks then a slash + //: matches zero or more directories. For example, "`a/**/b`" + //: matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on. + //: + //: - Other consecutive asterisks are considered invalid. + rule = new FileRule(result, definition); + } + + } + } catch (ParserException e) { + e.printStackTrace(); + return new InvalidRule(null, definition, e.getMessage()); + } + + return rule; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 128686b615b..386e37e3f0d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -77,6 +77,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co "string", "bool?", "double?", + "decimal?", "int?", "long?", "float?", @@ -112,7 +113,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co typeMapping.put("float", "float?"); typeMapping.put("long", "long?"); typeMapping.put("double", "double?"); - typeMapping.put("number", "double?"); + typeMapping.put("number", "decimal?"); typeMapping.put("datetime", "DateTime?"); typeMapping.put("date", "DateTime?"); typeMapping.put("file", "System.IO.Stream"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 99fab6e5444..fbb2831ab8b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -8,10 +8,12 @@ import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.*; -public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen -{ +public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen { /** * Name of the sub-directory in "src/main/resource" where to find the * Mustache template for the JAX-RS Codegen. @@ -19,10 +21,13 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; protected String implFolder = "src/main/java"; protected String title = "Swagger Server"; + static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class); public AbstractJavaJAXRSServerCodegen() { super(); + dateLibrary = "legacy"; + apiTestTemplateFiles.clear(); // TODO: add test template } @Override @@ -198,4 +203,5 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen public boolean shouldOverwrite(String filename) { return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 9e30ae657c8..cc41f3ea297 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -1,62 +1,73 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.*; -import io.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - import org.apache.commons.lang3.StringUtils; +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.FileProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { protected String modelPropertyNaming= "camelCase"; protected Boolean supportsES6 = true; - public AbstractTypeScriptClientCodegen() { - super(); - supportsInheritance = true; - setReservedWordsLowerCase(Arrays.asList( - // local variable names used in API methods (endpoints) - "varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred", - "requestOptions", - // Typescript reserved words - "abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield")); + public AbstractTypeScriptClientCodegen() { + super(); + supportsInheritance = true; + setReservedWordsLowerCase(Arrays.asList( + // local variable names used in API methods (endpoints) + "varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred", + "requestOptions", + // Typescript reserved words + "abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield")); - languageSpecificPrimitives = new HashSet(Arrays.asList( - "string", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object", + languageSpecificPrimitives = new HashSet(Arrays.asList( + "string", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object", "Array", "Date", "number", "any" - )); - instantiationTypes.put("array", "Array"); + )); + instantiationTypes.put("array", "Array"); - typeMapping = new HashMap(); - typeMapping.put("Array", "Array"); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "number"); - typeMapping.put("float", "number"); - typeMapping.put("number", "number"); - typeMapping.put("long", "number"); - typeMapping.put("short", "number"); - typeMapping.put("char", "string"); - typeMapping.put("double", "number"); - typeMapping.put("object", "any"); - typeMapping.put("integer", "number"); - typeMapping.put("Map", "any"); - typeMapping.put("DateTime", "Date"); + typeMapping = new HashMap(); + typeMapping.put("Array", "Array"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "number"); + typeMapping.put("float", "number"); + typeMapping.put("number", "number"); + typeMapping.put("long", "number"); + typeMapping.put("short", "number"); + typeMapping.put("char", "string"); + typeMapping.put("double", "number"); + typeMapping.put("object", "any"); + typeMapping.put("integer", "number"); + typeMapping.put("Map", "any"); + typeMapping.put("DateTime", "Date"); //TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); @@ -66,7 +77,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false")); - } + } @Override public void processOpts() { @@ -104,24 +115,24 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } @Override - public String toParamName(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'. + public String toParamName(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'. - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; - // camelize the variable name - // pet_id => petId - name = camelize(name, true); + // camelize 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); + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); - return name; - } + return name; + } @Override public String toVarName(String name) { @@ -130,70 +141,70 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } @Override - public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + public String toModelName(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(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + String modelName = camelize("model_" + name); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); } - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; + @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(); + 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) { + return "any"; } + return super.getTypeDeclaration(p); + } - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - String modelName = camelize("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // model name starts with number - if (name.matches("^\\d.*")) { - String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @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(); - 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) { - return "any"; - } - return super.getTypeDeclaration(p); - } - - @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; - } else - type = swaggerType; - return toModelName(type); - } + @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; + } else + type = swaggerType; + return toModelName(type); + } @Override public String toOperationId(String operationId) { @@ -217,8 +228,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp 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'"); } } @@ -232,9 +243,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp 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'"); + default: throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 282c4d88647..d11cc6ce0a3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -33,6 +33,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // requestPackage and authPackage are used by the "volley" template/library protected String requestPackage = "io.swagger.client.request"; protected String authPackage = "io.swagger.client.auth"; + protected String gradleWrapperPackage = "gradle.wrapper"; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; @@ -89,8 +90,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); - supportedLibraries.put("", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1"); - supportedLibraries.put("volley", "HTTP client: Volley 1.0.19"); + supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); + supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setEnum(supportedLibraries); cliOptions.add(library); @@ -382,23 +383,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi additionalProperties.put( "modelDocPath", modelDocPath ); if (StringUtils.isEmpty(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - addSupportingFilesForDefault(); - } else if ("volley".equals(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - addSupportingFilesForVolley(); + setLibrary("volley"); // set volley as the default library } + + // determine which file (mustache) to add based on library + if ("volley".equals(getLibrary())) { + addSupportingFilesForVolley(); + } else if ("httpclient".equals(getLibrary())) { + addSupportingFilesForHttpClient(); + } else { + throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); + } + } - private void addSupportingFilesForDefault() { + 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")); @@ -415,9 +419,25 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi (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")); @@ -446,6 +466,14 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi (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() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 2fc8738f067..4265f67709c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -137,6 +137,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { @Override public void processOpts() { super.processOpts(); + Boolean excludeTests = false; + + if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); + } apiPackage = "Api"; modelPackage = "Model"; @@ -218,6 +223,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", + clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", @@ -226,17 +233,29 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { clientPackageDir, "ApiException.cs")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", + clientPackageDir, "ExceptionFactory.cs")); supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh")); + // shell script to run the nunit test + supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.sh")); // copy package.config to nuget's standard location for project-level installs supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config")); - supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); + // .travis.yml for travis-ci.org CI + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); + + if(Boolean.FALSE.equals(excludeTests)) { + supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); + } 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")); + // apache v2 license + // UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally + //supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); if (optionalAssemblyInfoFlag) { supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); @@ -245,11 +264,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj")); - // TODO: Check if test project output is enabled, partially related to #2506. Should have options for: - // 1) No test project - // 2) No model tests - // 3) No api tests - supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj")); + if(Boolean.FALSE.equals(excludeTests)) { + supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj")); + } } additionalProperties.put("apiDocPath", apiDocPath); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 4e34424eab7..efcde6d8c41 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -146,7 +146,9 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go")); supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go")); supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go")); + supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java index 2812d2a301b..5b26662531f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java @@ -19,6 +19,7 @@ public class GroovyClientCodegen extends JavaClientCodegen { outputFolder = "generated-code/groovy"; modelTemplateFiles.put("model.mustache", ".groovy"); apiTemplateFiles.put(templateFileName, ".groovy"); + apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "Groovy"; apiPackage = "io.swagger.api"; @@ -26,6 +27,7 @@ public class GroovyClientCodegen extends JavaClientCodegen { configPackage = "io.swagger.configuration"; invokerPackage = "io.swagger.api"; artifactId = "swagger-spring-mvc-server"; + dateLibrary = "legacy"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 324ca56e70b..08147f60f36 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -7,10 +7,8 @@ import io.swagger.models.properties.*; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Swagger; -import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.*; -import java.io.File; public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig { @@ -432,7 +430,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf case "pipes": return "(QueryList 'PipeSeparated (" + type + "))"; case "multi": return "(QueryList 'MultiParamArray (" + type + "))"; default: - throw new NotImplementedException(); + throw new UnsupportedOperationException(); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index bc839f07d18..c80bb0ed23f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -30,13 +30,16 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; - protected String dateLibrary = "default"; + protected String dateLibrary = "joda"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-java-client"; protected String artifactVersion = "1.0.0"; 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 gradleWrapperPackage = "gradle.wrapper"; protected String localVariablePrefix = ""; protected boolean fullJavaUtil; protected String javaUtilPrefix = ""; @@ -52,6 +55,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "java"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); + apiTestTemplateFiles.put("api_test.mustache", ".java"); embeddedTemplateDir = templateDir = "Java"; apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; @@ -107,12 +111,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); - supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); - supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)"); + supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); @@ -124,6 +128,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { Map dateOptions = new HashMap(); dateOptions.put("java8", "Java 8 native"); dateOptions.put("joda", "Joda"); + dateOptions.put("legacy", "Legacy java.util.Date"); dateLibrary.setEnum(dateOptions); cliOptions.add(dateLibrary); @@ -257,12 +262,22 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - writeOptional(outputFolder, new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); + + //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") ); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); @@ -281,6 +296,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // generate markdown docs modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + //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") ); } else if ("okhttp-gson".equals(getLibrary())) { // generate markdown docs modelDocTemplateFiles.put("model_doc.mustache", ".md"); @@ -293,14 +316,49 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + + //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") ); } else if (usesAnyRetrofitLibrary()) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); + + //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") ); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + + //generate markdown docs for retrofit2 + if ( usesRetrofit2Library() ){ + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + } + } else if("jersey2".equals(getLibrary())) { // generate markdown docs modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); + + //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") ); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } if(additionalProperties.containsKey(DATE_LIBRARY)) { @@ -366,6 +424,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/'); } + @Override + public String apiTestFileFolder() { + return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/'); + } + @Override public String modelFileFolder() { return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/'); @@ -391,6 +454,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(name); } + @Override + public String toApiTestFilename(String name) { + return toApiName(name) + "Test"; + } + @Override public String toVarName(String name) { // sanitize name diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index 0cf59e5faa7..8a08bf758a3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -25,9 +25,11 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen { sourceFolder = "src/gen/java"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); + apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "JavaInflector"; invokerPackage = "io.swagger.handler"; artifactId = "swagger-inflector-server"; + dateLibrary = "legacy"; apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index 52f3eb8d844..72f969403bf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -6,6 +6,8 @@ import io.swagger.models.Operation; import java.io.File; import java.util.*; +import org.apache.commons.lang3.StringUtils; + public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaJerseyServerCodegen() { super(); @@ -26,7 +28,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { additionalProperties.put("title", title); - embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18"; + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME; for ( int i = 0; i < cliOptions.size(); i++ ) { if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) { @@ -36,13 +38,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { } CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setDefault(DEFAULT_LIBRARY); - Map supportedLibraries = new LinkedHashMap(); - - supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1"); - supportedLibraries.put("jersey2", "Jersey core 2.x"); + supportedLibraries.put("jersey1", "Jersey core 1.x"); + supportedLibraries.put("jersey2", "Jersey core 2.x (default)"); library.setEnum(supportedLibraries); + library.setDefault("jersey1"); cliOptions.add(library); cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); @@ -73,16 +73,35 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { public void processOpts() { super.processOpts(); + // set jersey2 as default + if (StringUtils.isEmpty(library)) { + setLibrary("jersey2"); + } + + supportingFiles.clear(); + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); - if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) { + if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } - supportingFiles.clear(); + if (additionalProperties.containsKey("dateLibrary")) { + setDateLibrary(additionalProperties.get("dateLibrary").toString()); + additionalProperties.put(dateLibrary, "true"); + } + + 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 ( "java8".equals(dateLibrary) ) { + supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); + } + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); @@ -91,40 +110,8 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java")); - writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); - - if ( additionalProperties.containsKey("dateLibrary") ) { - setDateLibrary(additionalProperties.get("dateLibrary").toString()); - additionalProperties.put(dateLibrary, "true"); - } - if(DEFAULT_LIBRARY.equals(library) || library == null) { - if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) { - // set to the default location - templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18"; - } - else { - templateDir += File.separator + "jersey1_18"; - } - } - if("jersey2".equals(library)) { - if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) { - // set to the default location - templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey2"; - } - else { - templateDir += File.separator + "jersey2"; - } - } - - 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 ( "java8".equals(dateLibrary) ) { - supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); - } } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index b919430035d..4c13fd50f0b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -31,8 +31,10 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); + apiTestTemplateFiles.clear(); // TODO: add test template apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; + dateLibrary = "legacy"; additionalProperties.put("title", title); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 46b6083e2e4..cc1e77649e5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -1,14 +1,7 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenParameter; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.*; +import io.swagger.models.Model; import io.swagger.models.properties.*; import java.io.File; @@ -26,10 +19,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String POD_NAME = "podName"; public static final String AUTHOR_NAME = "authorName"; public static final String AUTHOR_EMAIL = "authorEmail"; - public static final String GIT_REPO_URL = "gitRepoURL"; public static final String LICENSE = "license"; - - public static final String BinaryDataType = "ObjcClientCodegenBinaryData"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; + public static final String CORE_DATA = "coreData"; protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; @@ -37,11 +30,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String classPrefix = "SWG"; protected String authorName = "Swagger"; protected String authorEmail = "apiteam@swagger.io"; - protected String license = "MIT"; + protected String license = DEFAULT_LICENSE; protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; protected String[] specialWords = {"new", "copy"}; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; + + protected boolean generateCoreData = false; protected Set advancedMapingTypes = new HashSet(); @@ -70,8 +68,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { defaultIncludes.add("NSDictionary"); defaultIncludes.add("NSMutableArray"); defaultIncludes.add("NSMutableDictionary"); - - defaultIncludes.add(BinaryDataType); + defaultIncludes.add("NSManagedObject"); + defaultIncludes.add("NSData"); advancedMapingTypes.add("NSDictionary"); advancedMapingTypes.add("NSArray"); @@ -88,6 +86,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives.add("NSString"); languageSpecificPrimitives.add("NSObject"); languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSData"); languageSpecificPrimitives.add("NSURL"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("BOOL"); @@ -109,8 +108,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); - typeMapping.put("binary", BinaryDataType); - typeMapping.put("ByteArray", BinaryDataType); + typeMapping.put("binary", "NSData"); + typeMapping.put("ByteArray", "NSData"); + typeMapping.put("byte", "NSData"); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -143,6 +143,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSString", "NSDate", + "NSData", "NSURL", "NSDictionary") ); @@ -151,6 +152,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { instantiationTypes.put("map", "NSMutableDictionary"); cliOptions.clear(); + cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") .defaultValue("SWG")); cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") @@ -161,7 +163,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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(LICENSE, "License to use in the podspec file.").defaultValue("MIT")); } @Override @@ -191,6 +192,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); } + if (additionalProperties.containsKey(CORE_DATA)) { + Object coreData = additionalProperties.get(CORE_DATA); + if(((String)coreData).equalsIgnoreCase("true")) { + generateCoreData = true; + } + } if (additionalProperties.containsKey(CLASS_PREFIX)) { setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); } @@ -207,8 +214,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); } - if (additionalProperties.containsKey(LICENSE)) { - setLicense((String) additionalProperties.get(LICENSE)); + if(generateCoreData) { + modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); + modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); + modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); + modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); } additionalProperties.put(POD_NAME, podName); @@ -222,36 +232,41 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + additionalProperties.put("useCoreData", generateCoreData); - String swaggerFolder = podName; + modelPackage = podName; + apiPackage = podName; - modelPackage = swaggerFolder; - apiPackage = swaggerFolder; - - supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); + 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("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.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-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); 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")); - + 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")); + } } @Override @@ -289,8 +304,81 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelNameWithoutReservedWordCheck(type); } + public CodegenProperty coreDatafromProperty(String name, Property p) { + CodegenProperty property = fromProperty(name, p); + if(!generateCoreData) { + return property; + } + property.baseType = getTypeCoreDataDeclaration(p); + return property; + } + @Override public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property 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, + // return container type with pointer, e.g. `NSArray**' + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + // In this condition, type of property 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 + "*>*"; + } + } + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "*"; + } else { + for (String s : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(s)) { + return getSwaggerType(p) + "*"; + } + } + return getSwaggerType(p) + "*"; + } + } else { + String swaggerType = getSwaggerType(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) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this condition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this condition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } + } + + + public String getTypeCoreDataDeclaration(Property p) { if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); @@ -300,10 +388,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - - if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) { - return "NSData*"; - } // In this codition, type of property p is array of primitive, // return container type with pointer, e.g. `NSArray**' if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { @@ -324,7 +408,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Property inner = mp.getAdditionalProperties(); String innerTypeDeclaration = getTypeDeclaration(inner); - + if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } @@ -360,6 +444,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } + @Override public String toModelName(String type) { // model name cannot use reserved keyword @@ -454,12 +543,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage(); + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); } @Override public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage(); + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); } @Override @@ -576,6 +669,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + super.postProcessModelProperty(model,property); + property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); + } + /** * Return the default value of the property * diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 738ffd4e0d5..ac76770c1a4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; @@ -13,6 +14,7 @@ import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.HashSet; import java.util.regex.Matcher; @@ -32,10 +34,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; protected String invokerPackage = "Swagger\\Client"; - protected String composerVendorName = "swagger"; - protected String composerProjectName = "swagger-client"; + protected String composerVendorName = null; + protected String composerProjectName = null; protected String packagePath = "SwaggerClient-php"; - protected String artifactVersion = "1.0.0"; + protected String artifactVersion = null; protected String srcBasePath = "lib"; protected String testBasePath = "test"; protected String docsBasePath = "docs"; @@ -126,7 +128,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); 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(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC)); 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")); } @@ -163,6 +167,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { .replaceAll(regLastPathSeparator+ "$", ""); } + @Override + public String escapeText(String input) { + if (input != null) { + // Trim the string to avoid leading and trailing spaces. + return super.escapeText(input).trim(); + } + return input; + } + @Override public CodegenType getTag() { return CodegenType.CLIENT; @@ -214,12 +227,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); } + if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) { + this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID)); + } else { + additionalProperties.put(CodegenConstants.GIT_USER_ID, gitUserId); + } + if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) { this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); } else { additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); } + if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) { + this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID)); + } else { + additionalProperties.put(CodegenConstants.GIT_REPO_ID, gitRepoId); + } + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); } else { @@ -248,7 +273,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); - + // apache v2 license + supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE")); } @Override @@ -626,4 +652,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // process enum in models return postProcessModelsEnum(objs); } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.vendorExtensions.put("x-testOperationId", camelize(op.operationId)); + } + return objs; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 113c6a6e1c1..51bd143ba8f 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -15,7 +15,6 @@ 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; @@ -116,6 +115,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public void processOpts() { super.processOpts(); + Boolean excludeTests = false; + + 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)); @@ -144,14 +148,23 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig apiPackage = swaggerFolder + File.separatorChar + "apis"; supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); + supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); + supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); + + 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")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java new file mode 100644 index 00000000000..4bb4c8e883c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -0,0 +1,320 @@ +package io.swagger.codegen.languages; + +import java.text.SimpleDateFormat; +import java.util.Date; +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.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 java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); + private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); + + protected String gemName; + protected String moduleName; + protected String gemVersion = "1.0.0"; + protected String appFolder = "app"; + protected String channelsFolder = appFolder + File.separator + "channels"; + protected String applicationCableFolder = channelsFolder + File.separator + "application_cable"; + protected String controllersFolder = appFolder + File.separator + "controllers"; + protected String jobsFolder = appFolder + File.separator + "jobs"; + protected String mailersFolder = appFolder + File.separator + "mailers"; + protected String modelsFolder = appFolder + File.separator + "models"; + protected String viewsFolder = appFolder + File.separator + "views"; + protected String layoutsFolder = viewsFolder + File.separator + "layouts"; + protected String binFolder = "bin"; + protected String configFolder = "config"; + protected String environmentsFolder = configFolder + File.separator + "config"; + protected String initializersFolder = configFolder + File.separator + "initializers"; + protected String localesFolder = configFolder + File.separator + "locales"; + protected String dbFolder = "db"; + protected String migrateFolder = dbFolder + File.separator + "migrate"; + protected String libFolder = "lib"; + protected String tasksFolder = libFolder + File.separator + "tasks"; + protected String logFolder = "log"; + protected String publicFolder = "public"; + protected String testFolder = "test"; + protected String tmpFolder = "tmp"; + protected String cacheFolder = tmpFolder + File.separator + "cache"; + protected String pidFolder = tmpFolder + File.separator + "pids"; + protected String socketsFolder = tmpFolder + File.separator + "sockets"; + protected String vendorFolder = "vendor"; + + public Rails5ServerCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "rails5"; + apiPackage = "app/controllers"; + apiTemplateFiles.put("controller.mustache", ".rb"); + + modelPackage = "app/models"; + modelTemplateFiles.put("model.mustache", ".rb"); + + embeddedTemplateDir = templateDir = "rails5"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + setReservedWordsLowerCase( + Arrays.asList( + "__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.put("string", "string"); + typeMapping.put("char", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("integer", "integer"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("double", "decimal"); + typeMapping.put("number", "float"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("binary", "string"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("UUID", "string"); + + // remove modelPackage and apiPackage added by default + cliOptions.clear(); + } + + @Override + public void processOpts() { + super.processOpts(); + + // use constant model/api package (folder path) + //setModelPackage("models"); + setApiPackage("app/controllers"); + + supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile")); + supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); + supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb")); + supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb")); + supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb")); + supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb")); + supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb")); + supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb")); + supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb")); + supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb")); + supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle")); + supportingFiles.add(new SupportingFile("rails", binFolder, "rails")); + supportingFiles.add(new SupportingFile("rake", binFolder, "rake")); + supportingFiles.add(new SupportingFile("setup", binFolder, "setup")); + supportingFiles.add(new SupportingFile("update", binFolder, "update")); + supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb")); + supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb")); + supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb")); + supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb")); + supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb")); + supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb")); + supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb")); + supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb")); + supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb")); + supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb")); + supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb")); + supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb")); + supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml")); + supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb")); + supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb")); + supportingFiles.add(new SupportingFile("cable.yml", configFolder, "cable.yml")); + supportingFiles.add(new SupportingFile("database.yml", configFolder, "database.yml")); + supportingFiles.add(new SupportingFile("environment.rb", configFolder, "environment.rb")); + supportingFiles.add(new SupportingFile("puma.rb", configFolder, "puma.rb")); + supportingFiles.add(new SupportingFile("routes.mustache", configFolder, "routes.rb")); + supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); + supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); + supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); + supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb")); + supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); + supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); + supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", logFolder, ".keep")); + supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html")); + supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html")); + supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html")); + supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png")); + supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png")); + supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("test_helper.rb", testFolder, "test_helper.rb")); + supportingFiles.add(new SupportingFile(".keep", cacheFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", pidFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", socketsFolder, ".keep")); + supportingFiles.add(new SupportingFile("restart.txt", tmpFolder, "restart.txt")); + supportingFiles.add(new SupportingFile(".keep", vendorFolder, ".keep")); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "rails5"; + } + + @Override + public String getHelp() { + return "Generates a Rails5 server library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @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) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String toDefaultValue(Property p) { + return "null"; + } + + @Override + public String toVarName(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'. + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // camelize (lower first character) the variable name + // petId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + return "string"; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } + + @Override + 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'. + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_controllers"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "ApiController"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Controller"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(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); + } + } + return super.postProcessSupportingFileData(objs); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 6655a28f1d5..0db5598f7f0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -5,6 +5,7 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -224,6 +225,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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("LICENSE", "", "LICENSE")); + + // test files should not be overwritten writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb")); writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb")); @@ -527,6 +531,57 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return camelize(name) + "Api"; } + @Override + public String toEnumValue(String value, String datatype) { + if ("Integer".equals(datatype) || "Float".equals(datatype)) { + return value; + } else { + return "\"" + escapeText(value) + "\""; + } + } + + @Override + public String toEnumVarName(String name, String datatype) { + // number + if ("Integer".equals(datatype) || "Float".equals(datatype)) { + String varName = new String(name); + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // string + String enumName = sanitizeName(underscore(name).toUpperCase()); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return "N" + enumName; + } else { + return enumName; + } + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = underscore(toModelName(property.name)).toUpperCase(); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return "N" + enumName; + } else { + return enumName; + } + } + + @Override + public Map postProcessModels(Map objs) { + // process enum in models + return postProcessModelsEnum(objs); + } + @Override public String toOperationId(String operationId) { // rename to empty_method_name_1 (e.g.) if method name is empty diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 992693810da..12467f12efe 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -35,6 +35,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; protected String authScheme = ""; + protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean authPreemptive; protected boolean asyncHttpClient = !authScheme.isEmpty(); @@ -74,6 +75,17 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + // gradle settings + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + 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") ); importMapping.remove("List"); importMapping.remove("Set"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java index 070f5de6d03..dbed6bc98c4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java @@ -10,16 +10,20 @@ import java.util.*; public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{ public static final String CONFIG_PACKAGE = "configPackage"; public static final String BASE_PACKAGE = "basePackage"; + public static final String INTERFACE_ONLY = "interfaceOnly"; + public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; protected String title = "Petstore Server"; protected String configPackage = ""; protected String basePackage = ""; + protected boolean interfaceOnly = false; + protected boolean singleContentTypes = false; protected String templateFileName = "api.mustache"; public SpringBootServerCodegen() { super(); outputFolder = "generated-code/javaSpringBoot"; - modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put(templateFileName, ".java"); + apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "JavaSpringBoot"; apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; @@ -39,7 +43,9 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); - + cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); + supportedLibraries.clear(); supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub."); supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " + @@ -78,30 +84,37 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); } + if (additionalProperties.containsKey(INTERFACE_ONLY)) { + this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); + } + + if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { + this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); + } + supportingFiles.clear(); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("notFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); - - supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); - supportingFiles.add(new SupportingFile("homeController.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); - - supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", - (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); - - - supportingFiles.add(new SupportingFile("application.properties", - ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); + if(!this.interfaceOnly) { + apiTemplateFiles.put("apiController.mustache", "Controller.java"); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + supportingFiles.add(new SupportingFile("homeController.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); + supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", + (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); + supportingFiles.add(new SupportingFile("application.properties", + ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); + } } @Override @@ -118,9 +131,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege 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); @@ -131,10 +141,10 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege opList.add(co); co.baseName = basePath; } - + @Override public void preprocessSwagger(Swagger swagger) { - System.out.println("preprocessSwagger"); + super.preprocessSwagger(swagger); if ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); } @@ -147,7 +157,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege port = parts[1]; } } - + this.additionalProperties.put("serverPort", port); if (swagger != null && swagger.getPaths() != null) { for (String pathname : swagger.getPaths().keySet()) { @@ -255,6 +265,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege public void setBasePackage(String configPackage) { this.basePackage = configPackage; } + + public void setInterfaceOnly(boolean interfaceOnly) { + this.interfaceOnly = interfaceOnly; + } + + public void setSingleContentTypes(boolean singleContentTypes) { + this.singleContentTypes = singleContentTypes; + } @Override public Map postProcessModels(Map objs) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 8bd7e3c1f8e..47c67a4ec6d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -18,12 +18,14 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen outputFolder = "generated-code/javaSpringMVC"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put(templateFileName, ".java"); + apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "JavaSpringMVC"; apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; configPackage = "io.swagger.configuration"; invokerPackage = "io.swagger.api"; artifactId = "swagger-spring-mvc-server"; + dateLibrary = "legacy"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index ba846857cb9..6ec81c1c357 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -342,7 +342,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { // Ensure that the enum type doesn't match a reserved word or // the variable name doesn't match the generated enum type or the // Swift compiler will generate an error - if (isReservedWord(codegenProperty.datatypeWithEnum) || name.equals(codegenProperty.datatypeWithEnum)) { + if (isReservedWord(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) { codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum"; } } @@ -355,8 +355,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } - char[] separators = {'-', '_', ' '}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", ""); + char[] separators = {'-', '_', ' ', ':'}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); } @@ -502,6 +502,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = new String(name); @@ -525,8 +526,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(); + String enumName = toModelName(property.name); + // TODO: toModelName already does something for names starting with number, so this code is probably never called if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index a80e0f66ae0..6a945249af6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -5,12 +5,15 @@ import java.text.SimpleDateFormat; import java.util.Date; import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.SupportingFile; +import io.swagger.models.ModelImpl; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.FileProperty; import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.ObjectProperty; import io.swagger.models.properties.Property; public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCodegen { @@ -43,6 +46,12 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod 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 + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { + codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties()); + addImport(codegenModel, codegenModel.additionalPropertiesType); + } + @Override public String getName() { return "typescript-angular2"; @@ -106,14 +115,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod MapProperty mp = (MapProperty)p; inner = mp.getAdditionalProperties(); return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }"; + } else if(p instanceof FileProperty || p instanceof ObjectProperty) { + return "any"; } else { - return p instanceof FileProperty ? "any" : super.getTypeDeclaration(p); + return super.getTypeDeclaration(p); } } @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); + if(languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } return addModelPrefix(swaggerType); } @@ -121,13 +135,25 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return type; - } else + } else { + type = swaggerType; + } + + if (!startsWithLanguageSpecificPrimitiv(type)) { type = "models." + swaggerType; + } return type; } + private boolean startsWithLanguageSpecificPrimitiv(String type) { + for (String langPrimitive:languageSpecificPrimitives) { + if (type.startsWith(langPrimitive)) { + return true; + } + } + return false; + } + @Override public void postProcessParameter(CodegenParameter parameter) { super.postProcessParameter(parameter); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index c817162401e..90f778eae8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index d4207f09cc8..516d34b9810 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -42,7 +42,6 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME)); if(additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); } diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index 4629c4e17be..cb425df3563 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -1,22 +1,28 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache index e2a47317afe..c08f145a482 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 073966b0c21..7b72a7bab45 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index ad7b9051f05..4d54d84d337 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -78,12 +78,12 @@ public class {{classname}} { {{/formParams}} final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }; final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index b9a62a6b231..89ed524d37e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.util.Map; @@ -5,65 +7,74 @@ import java.util.List; {{>generatedAnnotation}} public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache b/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache index 93c5bc5b13a..bbb5b66f840 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache @@ -75,8 +75,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache new file mode 100644 index 00000000000..0a7639e0ec1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache @@ -0,0 +1,43 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index 931d17b0d04..f73a6f5b3f8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 265c74cb76f..26174fa3b59 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; @@ -6,6 +8,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index febabe33d64..0438f6a40b7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index 902f54a2e3a..ffc9923d1fe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache index 7ab35f6d890..002e9572f33 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache @@ -1,5 +1,7 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache index 32858aad3c3..7cf39af816c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar differ diff --git a/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache b/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 2d9fa23cf04..be2e2d5e3ab 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import feign.Feign; import feign.RequestInterceptor; @@ -22,7 +23,7 @@ import {{invokerPackage}}.auth.OAuth.AccessTokenListener; public class ApiClient { public interface Api {} - private ObjectMapper objectMapper; + protected ObjectMapper objectMapper; private String basePath = "{{basePath}}"; private Map apiAuthorizations; private Feign.Builder feignBuilder; @@ -128,6 +129,13 @@ public class ApiClient { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.registerModule(new JodaModule()); + return objectMapper; + } + + public ObjectMapper getObjectMapper(){ return objectMapper; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index fae7a93303d..c9d756d33ec 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -26,7 +26,7 @@ public interface {{classname}} extends ApiClient.Api { @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @Headers({ "Content-type: {{vendorExtensions.x-contentType}}", - "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}} + "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}} "{{paramName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, {{/hasMore}}{{/headerParams}} }) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache new file mode 100644 index 00000000000..303fda344e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache @@ -0,0 +1,44 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Before; +import org.junit.Test; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + api = new ApiClient().buildClient({{classname}}.class); + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache index 74ff86ebd1b..1df88d403a2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import {{invokerPackage}}.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache new file mode 100644 index 00000000000..37eabbd27b2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "com.brsanthu" % "migbase64" % "2.2" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 03323a65a03..df5b965984e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -149,19 +149,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 + ${jackson-version} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index 6c980b727fa..26cb9d7d946 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -76,12 +76,12 @@ public class {{classname}} { {{/formParams}} final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }; final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache new file mode 100644 index 00000000000..0a297497d9d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache @@ -0,0 +1,25 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", + "joda-time" % "joda-time" % "2.9.3", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache index bfc1aedbc11..4cc99a76ec3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.io.IOException; @@ -11,39 +13,39 @@ import java.util.List; * @param The return type */ public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 4c8e304ed97..3d6b3fe17f0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.Call; @@ -67,1073 +69,1234 @@ import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; } - ANDROID_SDK_VERSION = sdkVersion; - } - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private String basePath = "{{basePath}}"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; + private String basePath = "{{basePath}}"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; - private Map authentications; + private Map authentications; - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; - private InputStream sslCaCert; - private boolean verifyingSsl; + private InputStream sslCaCert; + private boolean verifyingSsl; - private OkHttpClient httpClient; - private JSON json; + private OkHttpClient httpClient; + private JSON json; - private HttpLoggingInterceptor loggingInterceptor; - - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); + private HttpLoggingInterceptor loggingInterceptor; /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + * Constructor for ApiClient */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); + public ApiClient() { + httpClient = new OkHttpClient(); - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; + verifyingSsl = true; - // Set default User-Agent. - setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); + json = new JSON(this); - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap();{{#authMethods}}{{#isBasic}} - authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} - authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} - authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); - public String getBasePath() { - return basePath; - } + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } + // Set default User-Agent. + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); - public OkHttpClient getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public JSON getJSON() { - return json; - } - - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string. - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - */ - public 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); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; } - if (valueCollection.isEmpty()){ - return params; + /** + * Set base path + * + * @param basePath Base path of the URL (e.g {{basePath}}) + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; } - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; } - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; } - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; } - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; } - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; } - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; } - if (respBody == null || "".equals(respBody)) { - return null; + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; } - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; + public DateFormat getDateFormat() { + return dateFormat; } - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * @see #execute(Call, Type) - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; } - } - /** - * #see executeAsync(Call, Type, ApiCallback) - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param The callback to be executed when the API call finishes - */ - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } - @Override - public void onResponse(Response response) throws IOException { - T result; + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { try { - respBody = response.body().string(); + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public 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); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + throw new ApiException(e); } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + if (respBody == null || "".equals(respBody)) { + return null; } - } - } - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The Content-Type guessed - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). - } else { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); } - } - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } } - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache index 452f4e1e982..82c86b3e215 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.util.List; @@ -9,38 +11,38 @@ import java.util.Map; * @param T The type of data that is deserialized from response body */ public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; + final private int statusCode; + final private Map> headers; + final private T data; - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } - public int getStatusCode() { - return statusCode; - } + public int getStatusCode() { + return statusCode; + } - public Map> getHeaders() { - return headers; - } + public Map> getHeaders() { + return headers; + } - public T getData() { - return data; - } + public T getData() { + return data; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 9cc1324acb6..b1be00ea985 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.google.gson.Gson; @@ -10,76 +12,118 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + public class JSON { - private ApiClient apiClient; - private Gson gson; + private ApiClient apiClient; + private Gson gson; - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .create(); - } - - public Gson getGson() { - return gson; - } - - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } } - } } class DateAdapter implements JsonSerializer, JsonDeserializer { private final ApiClient apiClient; + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ public DateAdapter(ApiClient apiClient) { super(); this.apiClient = apiClient; } + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { @@ -89,6 +133,16 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { String str = json.getAsJsonPrimitive().getAsString(); @@ -99,3 +153,62 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache index 57931ef4cfc..d6570bd0d3b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.MediaType; @@ -18,9 +20,9 @@ public class ProgressRequestBody extends RequestBody { } private final RequestBody requestBody; - + private final ProgressRequestListener progressListener; - + private BufferedSink bufferedSink; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { @@ -43,7 +45,7 @@ public class ProgressRequestBody extends RequestBody { if (bufferedSink == null) { bufferedSink = Okio.buffer(sink(sink)); } - + requestBody.writeTo(bufferedSink); bufferedSink.flush(); @@ -51,7 +53,7 @@ public class ProgressRequestBody extends RequestBody { private Sink sink(Sink sink) { return new ForwardingSink(sink) { - + long bytesWritten = 0L; long contentLength = 0L; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache index 061a95ac299..3f53133697c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.MediaType; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index 6c46a9aed9a..7abe897d42e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{package}}; import {{invokerPackage}}.ApiCallback; @@ -11,10 +13,6 @@ import {{invokerPackage}}.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; {{#imports}}import {{import}}; @@ -30,138 +28,138 @@ import java.util.Map; {{#operations}} public class {{classname}} { - private ApiClient {{localVariablePrefix}}apiClient; + private ApiClient {{localVariablePrefix}}apiClient; - public {{classname}}() { - this(Configuration.getDefaultApiClient()); - } - - public {{classname}}(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - public ApiClient getApiClient() { - return {{localVariablePrefix}}apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - {{#operation}} - /* Build call for {{operationId}} */ - private Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); - } - {{/required}}{{/allParams}} - - // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} - - final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); - if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); - - final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); - {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public {{classname}}() { + this(Configuration.getDefaultApiClient()); } - String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{{returnType}}}{{/returnType}} - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} - return {{localVariablePrefix}}resp.getData();{{/returnType}} - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} - } - - /** - * {{summary}} (asynchronously) - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; } - Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} - return {{localVariablePrefix}}call; - } - {{/operation}} + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{operationId}} */ + private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + // create path and map variables + String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); + if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); + + final String[] {{localVariablePrefix}}localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); + {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache index f3ed85d980b..320903b0319 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; @@ -10,32 +12,32 @@ import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 4e7b0d1c395..d05d7746e89 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -98,5 +98,6 @@ dependencies { compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' testCompile 'junit:junit:4.12' } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index bee8e03fa0e..1352db97988 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -13,6 +13,8 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.6.2", - "junit" % "junit" % "4.12.0" % "test" + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" ) ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache index 4bd6d5638b4..0c262eaa3a3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{package}}; import java.util.Objects; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache index f7af4c89f2f..213acb31568 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache @@ -2,19 +2,19 @@ * {{^description}}Gets or Sets {{name}}{{/description}}{{#description}}{{description}}{{/description}} */ public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) - {{{name}}}({{{value}}}){{^-last}}, + {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} - private {{dataType}} value; + private {{dataType}} value; - {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) { - this.value = value; - } + {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) { + this.value = value; + } - @Override - public String toString() { - return String.valueOf(value); - } + @Override + public String toString() { + return String.valueOf(value); + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache index 30ebf3febb6..bb69f71d24b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache @@ -1,20 +1,20 @@ - /** - * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} - */ - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) - {{{name}}}({{{value}}}){{^-last}}, + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ + public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} - private {{datatype}} value; + private {{datatype}} value; - {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) { - this.value = value; + {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } } - - @Override - public String toString() { - return String.valueOf(value); - } - } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache index b20499078a2..f2aad04d54b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache @@ -3,69 +3,93 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} + {{#vars}} + {{#isEnum}} +{{>libraries/common/modelInnerEnum}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} +{{>libraries/common/modelInnerEnum}} + {{/items}} + {{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} -{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}} - -{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}} - @SerializedName("{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; - {{/vars}} - - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - }{{^isReadOnly}} - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - }{{/isReadOnly}} - - {{/vars}} - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; } - if (o == null || getClass() != o.getClass()) { - return false; - }{{#hasVars}} - {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + + {{^isReadOnly}} + /** + * Set {{name}} + * + * @param {{name}} {{name}} + */ + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/isReadOnly}} + {{/vars}} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && {{/hasMore}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} - return true;{{/hasVars}} - } - - @Override - public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); - {{/vars}}sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index 7f08e5afb58..b1ec0b62461 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -104,28 +105,6 @@ 1.7 - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - - @@ -149,6 +128,11 @@ gson ${gson-version} + + joda-time + joda-time + ${jodatime-version} + @@ -159,10 +143,12 @@ - 1.5.8 + 1.5.9 2.7.5 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index 183fb5f27ce..c7b86b66b9c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit.RestAdapter; import retrofit.client.OkClient; @@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -108,6 +115,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -339,3 +348,61 @@ class GsonConverterWrapper implements Converter { } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache new file mode 100644 index 00000000000..a34cfe0e12b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache @@ -0,0 +1,44 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Before; +import org.junit.Test; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + api = new ApiClient().createService({{classname}}.class); + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache index 6be9ba586f3..179bda3b8d8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache @@ -99,6 +99,7 @@ ext { retrofit_version = "1.9.0" swagger_annotations_version = "1.5.8" junit_version = "4.12" + jodatime_version = "2.9.3" } dependencies { @@ -106,5 +107,6 @@ dependencies { compile "com.squareup.retrofit:retrofit:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache new file mode 100644 index 00000000000..56f6cee13ab --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", + "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index 9a917f19caf..c9991c230e5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -127,6 +127,11 @@ okhttp ${okhttp-version} + + joda-time + joda-time + ${jodatime-version} + @@ -140,6 +145,7 @@ 1.5.8 1.9.0 2.7.5 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index ad5f02c49e4..a4d62eece24 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -108,6 +115,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -346,3 +355,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache new file mode 100644 index 00000000000..a34cfe0e12b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache @@ -0,0 +1,44 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Before; +import org.junit.Test; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + api = new ApiClient().createService({{classname}}.class); + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache index 0997418a210..3b245597f21 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache @@ -1,6 +1,7 @@ package {{invokerPackage}}.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -85,42 +86,55 @@ public class OAuth implements Interceptor { updateAccessToken(null); } - // Build the request - Builder rb = request.newBuilder(); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response.code() == HTTP_UNAUTHORIZED ) { - updateAccessToken(requestAccessToken); - return intercept( chain ); - } - return response; } - public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; } } catch (OAuthSystemException e) { throw new IOException(e); @@ -128,6 +142,7 @@ public class OAuth implements Interceptor { throw new IOException(e); } } + return true; } public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index e56e682cfcd..fd2e94b582e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -97,25 +97,20 @@ ext { oltu_version = "1.0.1" retrofit_version = "2.0.2" swagger_annotations_version = "1.5.8" - junit_version = "4.12" -{{#useRxJava}} - rx_java_version = "1.1.3" -{{/useRxJava}} -{{^useRxJava}}{{/useRxJava}} + junit_version = "4.12"{{#useRxJava}} + rx_java_version = "1.1.3"{{/useRxJava}} + jodatime_version = "2.9.3" } dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" - compile "com.squareup.retrofit2:converter-gson:$retrofit_version" -{{#useRxJava}} + compile "com.squareup.retrofit2:converter-gson:$retrofit_version"{{#useRxJava}} compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" - compile "io.reactivex:rxjava:$rx_java_version" -{{/useRxJava}} -{{^useRxJava}}{{/useRxJava}} - + compile "io.reactivex:rxjava:$rx_java_version"{{/useRxJava}} compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache new file mode 100644 index 00000000000..ff564803b44 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache @@ -0,0 +1,23 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile",{{#useRxJava}} + "com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile", + "io.reactivex" % "rxjava" % "1.1.3" % "compile",{{/useRxJava}} + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index 30f6a71d285..2cc806ebbd3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -131,6 +131,11 @@ org.apache.oltu.oauth2 org.apache.oltu.oauth2.client ${oltu-version} + + + joda-time + joda-time + ${jodatime-version} {{#useRxJava}} io.reactivex @@ -153,9 +158,9 @@ 1.5.8 - 2.0.2 - {{#useRxJava}}1.1.3{{/useRxJava}} - 3.2.0 + 2.0.2{{#useRxJava}} + 1.1.3{{/useRxJava}} + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{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. + * + * 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. + */ diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 5d25496a1b3..7d57616610d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -18,8 +18,8 @@ public interface {{classname}} { {{#operation}} @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiException.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiException.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiOriginFilter.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiOriginFilter.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiOriginFilter.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiResponseMessage.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiResponseMessage.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiResponseMessage.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaDateTimeProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaDateTimeProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaDateTimeProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaLocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaLocalDateProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaLocalDateProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaLocalDateProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateTimeProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/NotFoundException.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/NotFoundException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/NotFoundException.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/README.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/README.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/README.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/StringUtil.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/StringUtil.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/StringUtil.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/allowableValues.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/allowableValues.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/allowableValues.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache similarity index 83% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache index 16f46ce0534..15442ad4748 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache @@ -25,8 +25,8 @@ import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; @Path("/{{baseName}}") -{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} -{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.Api(description = "the {{baseName}} API") {{>generatedAnnotation}} {{#operations}} @@ -36,8 +36,8 @@ public class {{classname}} { {{#operation}} @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiService.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceFactory.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceFactory.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceFactory.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceImpl.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bodyParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bodyParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bodyParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bootstrap.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bootstrap.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumClass.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumClass.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumClass.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumOuterClass.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumOuterClass.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumOuterClass.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/generatedAnnotation.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/generatedAnnotation.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/headerParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/headerParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/headerParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/jacksonJsonProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/jacksonJsonProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache index b9512d2b83c..738fe1c1440 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache @@ -1,6 +1,8 @@ package {{package}}; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pathParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pathParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pathParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pojo.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pojo.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pojo.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache similarity index 95% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache index 180450ce73f..96e657cac2b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache @@ -168,11 +168,12 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 - 1.18.1 - 1.6.3 - 4.8.1 + 1.19.1 + 1.7.21 + 4.12 2.5 + UTF-8 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/project/build.properties similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/project/build.properties rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/project/build.properties diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/project/plugins.sbt similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/project/plugins.sbt rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/project/plugins.sbt diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/queryParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/queryParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/returnTypes.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/returnTypes.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/returnTypes.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceBodyParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceBodyParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceBodyParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceFormParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceFormParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceFormParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceHeaderParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceHeaderParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceHeaderParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/servicePathParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/servicePathParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/servicePathParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceQueryParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/serviceQueryParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/serviceQueryParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/web.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/web.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/web.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiException.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiException.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiOriginFilter.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiOriginFilter.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiOriginFilter.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiResponseMessage.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiResponseMessage.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/ApiResponseMessage.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/JodaDateTimeProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaDateTimeProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/JodaDateTimeProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaLocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/JodaLocalDateProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaLocalDateProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/JodaLocalDateProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/LocalDateProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/LocalDateProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/LocalDateTimeProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateTimeProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/LocalDateTimeProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/NotFoundException.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/NotFoundException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/NotFoundException.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/README.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/README.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/README.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/StringUtil.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/StringUtil.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/StringUtil.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/allowableValues.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/allowableValues.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/allowableValues.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/api.mustache similarity index 83% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/api.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/api.mustache index 4200f4aca6e..e1eb66091ae 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/api.mustache @@ -23,8 +23,8 @@ import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; @Path("/{{baseName}}") -{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} -{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.Api(description = "the {{baseName}} API") {{>generatedAnnotation}} {{#operations}} @@ -34,8 +34,8 @@ public class {{classname}} { {{#operation}} @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiService.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiService.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiService.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiServiceFactory.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceFactory.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiServiceFactory.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiServiceImpl.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceImpl.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/apiServiceImpl.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/bodyParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bodyParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/bodyParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bootstrap.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/bootstrap.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bootstrap.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/bootstrap.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/enumClass.mustache similarity index 80% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumClass.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/enumClass.mustache index 6010e26704f..0867107d993 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/enumClass.mustache @@ -1,6 +1,6 @@ public enum {{{datatypeWithEnum}}} { - {{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}}, + {{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} private String value; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/enumOuterClass.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumOuterClass.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/enumOuterClass.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/formParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/formParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/formParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/generatedAnnotation.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/generatedAnnotation.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/generatedAnnotation.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/headerParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/headerParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/headerParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/jacksonJsonProvider.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/jacksonJsonProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/jacksonJsonProvider.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/model.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/model.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/model.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pathParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pathParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pathParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pojo.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pojo.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pojo.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pom.mustache similarity index 93% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pom.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pom.mustache index a2f59b53fe7..d69ff1632ec 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/pom.mustache @@ -134,12 +134,13 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 - 2.6 - 1.6.3 - 4.8.1 - 1.0.1 + 2.22.2 + 1.7.21 + 4.12 + 1.1.7 2.5 + UTF-8 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/project/build.properties similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/build.properties rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/project/build.properties diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/project/plugins.sbt similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/plugins.sbt rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/project/plugins.sbt diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/queryParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/queryParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/queryParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/returnTypes.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/returnTypes.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/returnTypes.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceBodyParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceBodyParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceBodyParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceFormParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceFormParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceFormParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceHeaderParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceHeaderParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceHeaderParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/servicePathParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/servicePathParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/servicePathParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceQueryParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceQueryParams.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/serviceQueryParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/web.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/web.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey2/web.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache index d83facaf646..6354f755b8b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache @@ -19,8 +19,8 @@ import javax.ws.rs.*; {{#operations}}{{#operation}}{{#isMultipart}}import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; {{/isMultipart}}{{/operation}}{{/operations}} @Path("/{{baseName}}") -{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} -{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -29,8 +29,8 @@ public class {{classname}} { {{#operation}} @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} public Response {{nickname}}({{#isMultipart}}MultipartFormDataInput input,{{/isMultipart}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{^isMultipart}}{{>formParams}},{{/isMultipart}}{{#isMultipart}}{{^isFormParam}},{{/isFormParam}}{{/isMultipart}}{{/allParams}}@Context SecurityContext securityContext) throws NotFoundException { return delegate.{{nickname}}({{#isMultipart}}input,{{/isMultipart}}{{#allParams}}{{^isMultipart}}{{paramName}},{{/isMultipart}}{{#isMultipart}}{{^isFormParam}}{{paramName}},{{/isFormParam}}{{/isMultipart}}{{/allParams}}securityContext); diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache index 8f9855eedf9..02d932b8aca 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache @@ -1,4 +1,4 @@ -# Swagger generated server +{{^interfaceOnly}}# Swagger generated server Spring Boot Server @@ -15,4 +15,31 @@ Start your server as an simple java application You can view the api documentation in swagger-ui by pointing to http://localhost:8080/ -Change default port value in application.properties \ No newline at end of file +Change default port value in application.properties{{/interfaceOnly}}{{#interfaceOnly}} +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache index 126fbf61a2c..bd0d7180529 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache @@ -7,9 +7,7 @@ import {{modelPackage}}.*; import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -23,12 +21,10 @@ import java.util.List; import static org.springframework.http.MediaType.*; -@Controller -@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE}) -@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API") +@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{>generatedAnnotation}} {{#operations}} -public class {{classname}} { +public interface {{classname}} { {{#operation}} @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { @@ -40,16 +36,14 @@ public class {{classname}} { }{{/hasAuthMethods}}) @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) - @RequestMapping(value = "{{{path}}}", - {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} - {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}} + produces = "{{{vendorExtensions.x-accepts}}}", + consumes = "{{{vendorExtensions.x-contentType}}}",{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}} + produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}} + consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}} method = RequestMethod.{{httpMethod}}) - public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) - throws NotFoundException { - // do some magic! - return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); - } + ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}); {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache new file mode 100644 index 00000000000..0cde913d660 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache @@ -0,0 +1,35 @@ +package {{apiPackage}}; + +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}Controller implements {{classname}} { + {{#operation}} + public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) { + // do some magic! + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache index 65e84817a23..d84de0c3376 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache @@ -1,2 +1 @@ -{{#isFormParam}}{{#notFile}} -@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache @@ -1 +1 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache index 297d5131d92..7c9e7356a0b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache index f6cc38793e7..53c3652cb45 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache @@ -14,7 +14,7 @@ 1.3.3.RELEASE - src/main/java + src/main/java{{^interfaceOnly}} org.springframework.boot @@ -27,7 +27,7 @@ - + {{/interfaceOnly}} @@ -50,5 +50,14 @@ springfox-swagger-ui ${springfox-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache index 3bb2afcb6cd..d935fb11fd3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache index 1af646a6908..970739e1b97 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache @@ -34,6 +34,8 @@ public class SwaggerDocumentationConfig { .select() .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) .build() + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api-j8-async.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api-j8-async.mustache index b11e5c2db20..90cb04104f0 100755 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api-j8-async.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api-j8-async.mustache @@ -49,8 +49,8 @@ public interface {{classname}} { @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", - {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} - {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + {{#hasProduces}}produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} + {{#hasConsumes}}consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} method = RequestMethod.{{httpMethod}}) default CallablereturnTypes}}>> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index ee02339909e..7fe7c5acf60 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -46,8 +46,8 @@ public class {{classname}} { @io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{{path}}}", - {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} - {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + {{#hasProduces}}produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} + {{#hasConsumes}}consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} method = RequestMethod.{{httpMethod}}) public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache new file mode 100644 index 00000000000..7fe7c5acf60 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache @@ -0,0 +1,61 @@ +package {{apiPackage}}; + +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Controller +@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE}) +@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API") +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + {{#operation}} + + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) + @RequestMapping(value = "{{{path}}}", + {{#hasProduces}}produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} + {{#hasConsumes}}consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + method = RequestMethod.{{httpMethod}}) + public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache index 257a4611db5..95c86d4bc0b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index f47085ad657..14abda4751c 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -74,8 +74,8 @@ }; var authNames = [<#authMethods>''<#hasMore>, ]; - var contentTypes = [<#consumes>''<#hasMore>, ]; - var accepts = [<#produces>''<#hasMore>, ]; + var contentTypes = [<#consumes>'<& mediaType>'<#hasMore>, ]; + var accepts = [<#produces>'<& mediaType>'<#hasMore>, ]; var returnType = <#returnType><&returnType><^returnType>null; return this.apiClient.callApi( diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache index f5aad995da5..0decb56e915 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache @@ -82,8 +82,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache index ca84decf9d3..915c99e8d40 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache @@ -1,8 +1,8 @@ { "name": "{{{projectName}}}", "version": "{{{projectVersion}}}", - "description": "{{{projectDescription}}}",{{#projectLicenseName}} - "license": "{{{projectLicenseName}}}",{{/projectLicenseName}} + "description": "{{{projectDescription}}}", + "license": "Apache-2.0", "main": "{{sourceFolder}}{{#invokerPackage}}/{{invokerPackage}}{{/invokerPackage}}/index.js", "scripts": { "test": "./node_modules/mocha/bin/mocha --recursive" diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index c84abac129c..f0d0fde5e57 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -27,6 +27,7 @@ io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen +io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringBootServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md index 8ec43e76497..db2dfccec36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -1,44 +1,54 @@ # TypeScript-Fetch -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: -* Node.JS +Environment +* Node.js * Webpack * Browserify -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) ### Installation ### -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: ``` import * as localName from 'npmName'; import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` import * as localName from './symlinkDir'; import {operationId} from './symlinkDir'; ``` -With CommonJS, the following syntaxes are supported: +The CommonJS syntax is as follows: ``` -import localName = require('npmName'); - import localName = require('./symlinkDir')'; -``` \ No newline at end of file +``` diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 67d61999aa0..20c303e40eb 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -1,7 +1,30 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; +import * as querystring from "querystring"; +import * as url from "url"; +import * as isomorphicFetch from "isomorphic-fetch"; +{{^supportsES6}} +import * as assign from "core-js/library/fn/object/assign"; +{{/supportsES6}} + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "{{basePath}}"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} {{#models}} {{#model}} @@ -13,24 +36,20 @@ import {assign} from './assign'; export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} {{#description}} - /** * {{{description}}} */ {{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } {{#hasEnums}} -export namespace {{classname}} { {{#vars}} {{#isEnum}} - -export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; +export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}"{{.}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; {{/isEnum}} {{/vars}} -} {{/hasEnums}} {{/model}} {{/models}} @@ -38,96 +57,111 @@ export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-las {{#apiInfo}} {{#apis}} {{#operations}} -//export namespace {{package}} { - 'use strict'; - -{{#description}} - /** - * {{&description}} - */ -{{/description}} - export class {{classname}} { - protected basePath = '{{basePath}}'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } +/** + * {{classname}} - fetch parameter creator{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}FetchParamCreactor = { {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}*/ - public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const localVarPath = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}}; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); -{{#hasFormParams}} - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - -{{/hasFormParams}} -{{#hasBodyParam}} - headerParams['Content-Type'] = 'application/json'; - -{{/hasBodyParam}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): FetchArgs { {{#allParams}} {{#required}} - // verify required parameter '{{paramName}}' is set - if (params.{{paramName}} == null) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } + // verify required parameter "{{paramName}}" is set + if (params["{{paramName}}"] == null) { + throw new Error("Missing required parameter {{paramName}} when calling {{nickname}}"); + } {{/required}} {{/allParams}} -{{#queryParams}} - if (params.{{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = params.{{paramName}}; - } + const baseUrl = `{{path}}`{{#pathParams}} + .replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}}; + let urlObj = url.parse(baseUrl, true); +{{#hasQueryParams}} + urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}} + "{{baseName}}": params.{{paramName}},{{/queryParams}} + }); +{{/hasQueryParams}} + let fetchOptions: RequestInit = { method: "{{httpMethod}}" }; -{{/queryParams}} -{{#headerParams}} - headerParams['{{baseName}}'] = params.{{paramName}}; + let contentTypeHeader: Dictionary; +{{#hasFormParams}} + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ {{#formParams}} + "{{baseName}}": params.{{paramName}},{{/formParams}} + }); +{{/hasFormParams}} +{{#hasBodyParam}} + contentTypeHeader = { "Content-Type": "application/json" };{{#bodyParam}} + if (params["{{paramName}}"]) { + fetchOptions.body = JSON.stringify(params["{{paramName}}"] || {}); + }{{/bodyParam}} +{{/hasBodyParam}} +{{#hasHeaderParam}} + fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}} + "{{baseName}}": params.{{paramName}},{{/headerParams}} + }, contentTypeHeader); +{{/hasHeaderParam}} +{{^hasHeaderParam}} + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } +{{/hasHeaderParam}} + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +{{/operation}} +} -{{/headerParams}} -{{#formParams}} - formParams['{{baseName}}'] = params.{{paramName}}; - -{{/formParams}} - let fetchParams = { - method: '{{httpMethod}}', - headers: headerParams, - {{#bodyParam}}body: JSON.stringify(params.{{paramName}}), - {{/bodyParam}} - {{#hasFormParams}}body: querystring.stringify(formParams), - {{/hasFormParams}} - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { +/** + * {{classname}} - functional programming interface{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}Fp = { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }{{/hasParams}}): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params{{/hasParams}}); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { - return response.json(); + return response{{#returnType}}.json(){{/returnType}}; } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; + throw response; } }); - } + }; + }, {{/operation}} +}; + +/** + * {{classname}} - object-oriented interface{{#description}} + * {{&description}}{{/description}} + */ +export class {{classname}} extends BaseAPI { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); } -//} +{{/operation}} +} + {{/operations}} {{/apis}} {{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache index e6379434b80..d885089fc9c 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -1,18 +1,19 @@ { "name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}", "version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}", - "private": true, + "license": "Apache-2.0", "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { - "isomorphic-fetch": "^2.2.1" + {{^supportsES6}}"core-js": "^2.4.0", + {{/supportsES6}}"isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", - "typings": "^0.8.1" + "typings": "^1.0.4" } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache index 06a057d7a49..25f414e9840 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache @@ -4,7 +4,8 @@ "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache index 38baf589fb9..e5bd78f06fe 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache @@ -1,9 +1,9 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { -{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", -{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914", + "globalDependencies": { {{^supportsES6}} + "core-js": "registry:dt/core-js#0.0.0+20160317120654",{{/supportsES6}} + "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } } diff --git a/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore b/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/_common/.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 +# Thsi 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/modules/swagger-codegen/src/main/resources/_common/LICENSE b/modules/swagger-codegen/src/main/resources/_common/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/_common/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache index 4d0e8c99675..7983a41edf6 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache @@ -20,7 +20,7 @@ object {{classname}} { {{>javadoc}} {{/javadocRenderer}} def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] = - ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) + ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) {{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}}) {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) diff --git a/modules/swagger-codegen/src/main/resources/android/api.mustache b/modules/swagger-codegen/src/main/resources/android/api.mustache index f3d0f7996de..5f786e503a0 100644 --- a/modules/swagger-codegen/src/main/resources/android/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/api.mustache @@ -73,7 +73,7 @@ public class {{classname}} { {{/headerParams}} String[] localVarContentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} + {{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}} }; String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; diff --git a/modules/swagger-codegen/src/main/resources/android/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/apiException.mustache index a6bcba75b7c..be5255e2568 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiException.mustache @@ -14,16 +14,16 @@ public class ApiException extends Exception { public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/api_doc.mustache b/modules/swagger-codegen/src/main/resources/android/api_doc.mustache index 2fdcab749ab..cd3888dfb06 100644 --- a/modules/swagger-codegen/src/main/resources/android/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/android/api_doc.mustache @@ -53,8 +53,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache index e153ce23ecf..a9b0f28edfb 100755 --- a/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/android/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/swagger-codegen/src/main/resources/android/gradle-wrapper.jar b/modules/swagger-codegen/src/main/resources/android/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/android/gradle-wrapper.jar differ diff --git a/modules/swagger-codegen/src/main/resources/android/gradle-wrapper.properties.mustache b/modules/swagger-codegen/src/main/resources/android/gradle-wrapper.properties.mustache new file mode 100644 index 00000000000..fa452523ac0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/gradle-wrapper.properties.mustache @@ -0,0 +1,6 @@ +#Mon May 16 21:00:11 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/modules/swagger-codegen/src/main/resources/android/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/android/gradlew.bat.mustache new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/gradlew.bat.mustache @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/android/gradlew.mustache b/modules/swagger-codegen/src/main/resources/android/gradlew.mustache new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/gradlew.mustache @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache index 55cec2f1279..08ce4409f7a 100644 --- a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache +++ b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache @@ -13,4 +13,4 @@ public class HttpPatch extends HttpPost { public String getMethod() { return METHOD_PATCH; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index 38c7f00cdaa..5d9ecb32066 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -81,7 +81,7 @@ public class {{classname}} { {{/headerParams}} String[] contentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} + {{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}} }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -167,7 +167,7 @@ public class {{classname}} { {{/headerParams}} String[] contentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} + {{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}} }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache index a6bcba75b7c..be5255e2568 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache @@ -14,16 +14,16 @@ public class ApiException extends Exception { public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache new file mode 100644 index 00000000000..b3c88d4be09 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache @@ -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="{{{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 crediential 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/android/libraries/volley/gitignore.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache new file mode 100644 index 00000000000..a8368751267 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache index d22bfa5693b..df99de87403 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache @@ -52,7 +52,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { return true;{{/hasVars}} } - @Override + @Override public int hashCode() { int result = 17; {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache index 4036bb32afb..80ba5feacab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache index 0df3f6e4ac4..6b0600e77b9 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache @@ -83,4 +83,4 @@ public class DeleteRequest extends Request { return headers; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache index 63803c3b481..ec225b5a46c 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache @@ -36,4 +36,4 @@ public class GetRequest extends StringRequest{ return headers; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache index 87270b48ebf..188fc5edb41 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache @@ -83,4 +83,4 @@ public class PatchRequest extends Request { return headers; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache index f11fddd25ef..02c7fdfb119 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache @@ -83,4 +83,4 @@ public class PostRequest extends Request { return headers; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache index 9e54c7cfe9a..571a921e56a 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache @@ -83,4 +83,4 @@ public class PutRequest extends Request { return headers; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/model.mustache b/modules/swagger-codegen/src/main/resources/android/model.mustache index d22bfa5693b..df99de87403 100644 --- a/modules/swagger-codegen/src/main/resources/android/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/model.mustache @@ -52,7 +52,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { return true;{{/hasVars}} } - @Override + @Override public int hashCode() { int result = 17; {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/android/pom.mustache b/modules/swagger-codegen/src/main/resources/android/pom.mustache index 0c00c55de1f..bf11a6625c5 100644 --- a/modules/swagger-codegen/src/main/resources/android/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/pom.mustache @@ -152,4 +152,4 @@ 4.8.1 4.3.6 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/android/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/android/settings.gradle.mustache index b8fd6c4c41f..ba0114cb176 100644 --- a/modules/swagger-codegen/src/main/resources/android/settings.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/android/settings.gradle.mustache @@ -1 +1 @@ -rootProject.name = "{{artifactId}}" \ No newline at end of file +rootProject.name = "{{artifactId}}" diff --git a/modules/swagger-codegen/src/main/resources/clojure/api.mustache b/modules/swagger-codegen/src/main/resources/clojure/api.mustache index a6b598fc610..cf821cfdd3c 100644 --- a/modules/swagger-codegen/src/main/resources/clojure/api.mustache +++ b/modules/swagger-codegen/src/main/resources/clojure/api.mustache @@ -14,8 +14,8 @@ <#hasOptionalParams> :query-params {<#queryParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> } <#hasOptionalParams> :form-params {<#formParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> }<#bodyParam> <#hasOptionalParams> :body-param - <#hasOptionalParams> :content-types [<#consumes>""<#hasMore> ] - <#hasOptionalParams> :accepts [<#produces>""<#hasMore> ] + <#hasOptionalParams> :content-types [<#consumes>"<& mediaType>"<#hasMore> ] + <#hasOptionalParams> :accepts [<#produces>"<& mediaType>"<#hasMore> ] <#hasOptionalParams> :auth-names [<#authMethods>"<&name>"<#hasMore> ]})<#hasOptionalParams>)) (defn @@ -24,4 +24,4 @@ ([<#allParams><#required><#isFile>^File ] (<#allParams><#required> nil)) <#hasOptionalParams>([<#allParams><#required><#isFile>^File <#hasOptionalParams>optional-params] <#hasOptionalParams> (:data (-with-http-info<#allParams><#required> <#hasOptionalParams> optional-params))<#hasOptionalParams>)) - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 2c0f8f681e3..6ab34216b9f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Collections; using System.Collections.Generic; @@ -16,10 +17,28 @@ using RestSharp; namespace {{packageName}}.Client { ///

- /// API client is mainly responible for making the HTTP call to the API backend. + /// API client is mainly responsible for making the HTTP call to the API backend. /// - public class ApiClient + public partial class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + /// /// Initializes a new instance of the class /// with default configuration and base path ({{basePath}}). @@ -159,6 +178,7 @@ namespace {{packageName}}.Client // set user agent RestClient.UserAgent = Configuration.UserAgent; + InterceptRequest(request); {{^supportsUWP}} var response = RestClient.Execute(request); {{/supportsUWP}} @@ -166,6 +186,8 @@ namespace {{packageName}}.Client // Using async method to perform sync call (uwp-only) var response = RestClient.ExecuteTaskAsync(request).Result; {{/supportsUWP}} + InterceptResponse(request, response); + return (Object) response; } {{#supportsAsync}} @@ -191,7 +213,9 @@ namespace {{packageName}}.Client var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); + InterceptResponse(request, response); return (Object)response; }{{/supportsAsync}} @@ -305,7 +329,7 @@ namespace {{packageName}}.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index e6185abc162..ad7c2264d78 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; namespace {{packageName}}.Client diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index 4b9f0a3a43c..d8c1b79e545 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Collections.Generic; diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index bf7f4d003ad..48b2886f6c9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Reflection; using System.Collections.Generic; @@ -79,6 +80,17 @@ namespace {{packageName}}.Client /// Configuration. public static Configuration Default = new Configuration(); + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + int status = (int) response.StatusCode; + if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); + if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + return null; + }; + /// /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache new file mode 100644 index 00000000000..c25b88ee614 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache @@ -0,0 +1,15 @@ +{{>partial_header}} + +using System; +using RestSharp; + +namespace {{packageName}}.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache new file mode 100644 index 00000000000..df236b8f8c8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -0,0 +1,33 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/LICENSE b/modules/swagger-codegen/src/main/resources/csharp/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache index 141d541a5b5..7a4c741ca4a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -1,4 +1,29 @@ + Debug @@ -46,10 +71,10 @@ - $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - {{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache b/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache index 57f6201600f..763780f657e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache @@ -4,9 +4,9 @@ VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +{{^excludeTests}}Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject -Global +{{/excludeTests}}Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU diff --git a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache index 0e0bd6c1671..f01a7e25dbb 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache @@ -1,4 +1,29 @@ + Debug @@ -46,10 +71,10 @@ - $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - {{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll @@ -58,10 +83,10 @@ {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll - $(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll - ..\packages\NUnit.2.6.3\lib\nunit.framework.dll - ..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll - {{binRelativePath}}\NUnit.2.6.3\lib\nunit.framework.dll + $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll + {{binRelativePath}}\NUnit.3.2.1\lib\nunit.framework.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 2b3f224cfc5..807155e4a45 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -13,7 +14,7 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface I{{classname}} + public interface I{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} @@ -72,8 +73,10 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class {{classname}} : I{{classname}} + public partial class {{classname}} : I{{classname}} { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -82,6 +85,8 @@ namespace {{packageName}}.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -102,6 +107,8 @@ namespace {{packageName}}.Api else this.Configuration = configuration; + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -122,7 +129,7 @@ namespace {{packageName}}.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing @@ -134,6 +141,22 @@ namespace {{packageName}}.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -196,7 +219,7 @@ namespace {{packageName}}.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { {{#consumes}} - "{{mediaType}}"{{#hasMore}}, {{/hasMore}} + "{{{mediaType}}}"{{#hasMore}}, {{/hasMore}} {{/consumes}} }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); @@ -204,7 +227,7 @@ namespace {{packageName}}.Api // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { {{#produces}} - "{{mediaType}}"{{#hasMore}}, {{/hasMore}} + "{{{mediaType}}}"{{#hasMore}}, {{/hasMore}} {{/produces}} }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); @@ -275,10 +298,11 @@ namespace {{packageName}}.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("{{operationId}}", localVarResponse); + if (exception != null) throw exception; + } {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -329,7 +353,7 @@ namespace {{packageName}}.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { {{#consumes}} - "{{mediaType}}"{{#hasMore}}, {{/hasMore}} + "{{{mediaType}}}"{{#hasMore}}, {{/hasMore}} {{/consumes}} }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); @@ -337,7 +361,7 @@ namespace {{packageName}}.Api // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { {{#produces}} - "{{mediaType}}"{{#hasMore}}, {{/hasMore}} + "{{{mediaType}}}"{{#hasMore}}, {{/hasMore}} {{/produces}} }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); @@ -409,10 +433,11 @@ namespace {{packageName}}.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("{{operationId}}", localVarResponse); + if (exception != null) throw exception; + } {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index 677ad3edbe1..c0a31d09377 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -87,8 +87,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache index cb345a93cc4..f3f1caeaf0a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.IO; using System.Collections.Generic; @@ -32,7 +33,7 @@ namespace {{packageName}}.Test [SetUp] public void Init() { - instance = new {{classname}}(); + instance = new {{classname}}(); } /// @@ -50,7 +51,8 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}InstanceTest() { - Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); + // test 'IsInstanceOfType' {{classname}} + Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); } {{#operations}}{{#operation}} @@ -60,12 +62,12 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}Test() { - // TODO: add unit test for the method '{{operationId}}' + // TODO uncomment below to test the method and replace null with proper value {{#allParams}} - {{{dataType}}} {{paramName}} = null; // TODO: replace null with proper value + //{{{dataType}}} {{paramName}} = null; {{/allParams}} - {{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}//Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} } {{/operation}}{{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache index f93437eb0c8..7aab3657090 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -1,15 +1,35 @@ #!/usr/bin/env bash +# +# 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. + frameworkVersion={{targetFrameworkNuget}} netfx=${frameworkVersion#net} +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" wget -nc https://nuget.org/nuget.exe; mozroots --import --sync mono nuget.exe install src/{{packageName}}/packages.config -o packages; -mkdir -p bin; -cp packages/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.8.0.3/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; +echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ @@ -18,3 +38,11 @@ System.Runtime.Serialization.dll \ -recurse:'src/{{packageName}}/*.cs' \ -doc:bin/{{packageName}}.xml \ -platform:anycpu + +if [ $? -ne 0 ] +then + echo "[ERROR] Compilation failed with exit code $?" + exit 1 +else + echo "[INFO] bin/{{{packageName}}}.dll was created successfully" +fi diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 7f6dcfe0713..5da333f4e72 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -1,3 +1,17 @@ +:: 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. + @echo off {{#supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319{{/supportsAsync}} @@ -8,7 +22,7 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll %CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 6c6ae8fdbb6..863d7ba93ef 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Linq; using System.IO; diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 4d4061a29fd..c8a00373ff2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -24,6 +24,13 @@ public {{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} { get; set; } {{/isEnum}} {{/vars}} + {{#hasRequired}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected {{classname}}() { } + {{/hasRequired}} /// /// Initializes a new instance of the class. /// @@ -32,9 +39,12 @@ /// {{#description}}{{description}}{{/description}}{{^description}}{{name}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. {{/isReadOnly}} {{/vars}} - public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} = null{{/isReadOnly}}{{#hasMoreNonReadOnly}}, {{/hasMoreNonReadOnly}}{{/vars}}) + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} = null{{^-last}}, {{/-last}}{{/readWriteVars}}) { - {{#vars}}{{^isReadOnly}}{{#required}}// to ensure "{{name}}" is required (not null) + {{#vars}} + {{^isReadOnly}} + {{#required}} + // to ensure "{{name}}" is required (not null) if ({{name}} == null) { throw new InvalidDataException("{{name}} is a required property for {{classname}} and cannot be null"); @@ -43,8 +53,12 @@ { this.{{name}} = {{name}}; } - {{/required}}{{/isReadOnly}}{{/vars}} - {{#vars}}{{^isReadOnly}}{{^required}} + {{/required}} + {{/isReadOnly}} + {{/vars}} + {{#vars}} + {{^isReadOnly}} + {{^required}} {{#defaultValue}}// use default value if no "{{name}}" provided if ({{name}} == null) { @@ -56,9 +70,11 @@ } {{/defaultValue}} {{^defaultValue}} - this.{{name}} = {{name}}; +this.{{name}} = {{name}}; {{/defaultValue}} - {{/required}}{{/isReadOnly}}{{/vars}} + {{/required}} + {{/isReadOnly}} + {{/vars}} } {{#vars}} @@ -79,7 +95,8 @@ { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); - {{#vars}}sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); {{/vars}} sb.Append("}\n"); return sb.ToString(); diff --git a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache index 0d20b9f03a3..233534a3348 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache @@ -1,3 +1,5 @@ +{{>partial_header}} + using NUnit.Framework; using System; @@ -23,7 +25,8 @@ namespace {{packageName}}.Test [TestFixture] public class {{classname}}Tests { - private {{classname}} instance; + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; /// /// Setup before each test @@ -31,7 +34,8 @@ namespace {{packageName}}.Test [SetUp] public void Init() { - instance = new {{classname}}(); + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); } /// @@ -49,7 +53,8 @@ namespace {{packageName}}.Test [Test] public void {{classname}}InstanceTest() { - Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); + // TODO uncomment below to test "IsInstanceOfType" {{classname}} + //Assert.IsInstanceOfType<{{classname}}> (instance, "variable 'instance' is a {{classname}}"); } {{#vars}} @@ -59,7 +64,7 @@ namespace {{packageName}}.Test [Test] public void {{name}}Test() { - // TODO: unit test for the property '{{name}}' + // TODO unit test for the property '{{name}}' } {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache new file mode 100644 index 00000000000..b4d1cd74ca6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# 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. + +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/SwaggerClientTest.dll" +rm src/IO.Swagger.Test/bin/Debug/{{{packageName}}}.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync +mono nuget.exe install src/{{{packageName}}}.Test/packages.config -o packages + +echo "[INFO] Install NUnit runners via NuGet" +mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild {{{packageName}}}.sln && \ + mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache index bd4428e687e..d9e5dea7d9f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -1,5 +1,5 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache index 5464714bcef..95192a480bf 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache @@ -1,6 +1,6 @@ - + - + diff --git a/modules/swagger-codegen/src/main/resources/csharp/partial_header.mustache b/modules/swagger-codegen/src/main/resources/csharp/partial_header.mustache new file mode 100644 index 00000000000..bf5862deafd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/partial_header.mustache @@ -0,0 +1,25 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * 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. + */ diff --git a/modules/swagger-codegen/src/main/resources/csharp/travis.mustache b/modules/swagger-codegen/src/main/resources/csharp/travis.mustache new file mode 100644 index 00000000000..983f06b7156 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/travis.mustache @@ -0,0 +1,21 @@ +# +# 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. +# +language: csharp +mono: + - latest +solution: {{{packageName}}}.sln +script: + - /bin/sh ./mono_nunit_test.sh diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index d8ee98569c1..cba12208b7d 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -37,7 +37,7 @@ class {{classname}} { {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} - List contentTypes = [{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; + List contentTypes = [{{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; List authNames = [{{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; diff --git a/modules/swagger-codegen/src/main/resources/go/.travis.yml b/modules/swagger-codegen/src/main/resources/go/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/modules/swagger-codegen/src/main/resources/go/LICENSE b/modules/swagger-codegen/src/main/resources/go/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 480db023f6b..b3e2f6db9af 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} package {{packageName}} {{#operations}} @@ -5,6 +6,7 @@ import ( "strings" "fmt" "errors" + "net/url" {{#imports}}"{{import}}" {{/imports}} ) @@ -50,7 +52,7 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ }{{/required}}{{/allParams}} headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -75,13 +77,26 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] - }{{#hasQueryParams}}{{#queryParams}} - - queryParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}}) + } + {{#hasQueryParams}} + {{#queryParams}} + {{#isListContainer}} + var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}" + if collectionFormat == "multi" { + for _, value := range {{paramName}} { + queryParams.Add("{{paramName}}", value) + } + } else { + queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) + } + {{/isListContainer}} + {{^isListContainer}} + queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) + {{/isListContainer}} {{/queryParams}}{{/hasQueryParams}} // to determine the Content-Type header - localVarHttpContentTypes := []string{ {{#consumes}}"{{mediaType}}", {{/consumes}} } + localVarHttpContentTypes := []string{ {{#consumes}}"{{{mediaType}}}", {{/consumes}} } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) @@ -90,7 +105,7 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ } // to determine the Accept header localVarHttpHeaderAccepts := []string{ - {{#produces}}"{{mediaType}}", + {{#produces}}"{{{mediaType}}}", {{/produces}} } // set Accept header diff --git a/modules/swagger-codegen/src/main/resources/go/api_client.mustache b/modules/swagger-codegen/src/main/resources/go/api_client.mustache index 88c5ce07e4e..be0f60673d8 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_client.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} package {{packageName}} import ( @@ -6,7 +7,7 @@ import ( "path/filepath" "reflect" "strings" - + "net/url" "github.com/go-resty/resty" ) @@ -47,7 +48,7 @@ func contains(source []string, containvalue string) bool { func (c *APIClient) CallAPI(path string, method string, postBody interface{}, headerParams map[string]string, - queryParams map[string]string, + queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) (*resty.Response, error) { @@ -79,17 +80,26 @@ func (c *APIClient) CallAPI(path string, method string, return nil, fmt.Errorf("invalid method %v", method) } -func (c *APIClient) ParameterToString(obj interface{}) string { +func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string { if reflect.TypeOf(obj).String() == "[]string" { - return strings.Join(obj.([]string), ",") - } else { - return obj.(string) + switch collectionFormat { + case "pipes": + return strings.Join(obj.([]string), "|") + case "ssv": + return strings.Join(obj.([]string), " ") + case "tsv": + return strings.Join(obj.([]string), "\t") + case "csv" : + return strings.Join(obj.([]string), ",") + } } + + return obj.(string) } func prepareRequest(postBody interface{}, headerParams map[string]string, - queryParams map[string]string, + queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) *resty.Request { @@ -104,7 +114,7 @@ func prepareRequest(postBody interface{}, // add query parameter, if any if len(queryParams) > 0 { - request.SetQueryParams(queryParams) + request.SetMultiValueQueryParams(queryParams) } // add form parameter, if any diff --git a/modules/swagger-codegen/src/main/resources/go/api_doc.mustache b/modules/swagger-codegen/src/main/resources/go/api_doc.mustache index e91082ffc99..3c3444474ee 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_doc.mustache @@ -35,8 +35,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/go/api_response.mustache b/modules/swagger-codegen/src/main/resources/go/api_response.mustache index a15293f4402..9bacc9578e4 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_response.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_response.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} package {{packageName}} import ( diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache index 463f77c54dc..fbc22f603d0 100644 --- a/modules/swagger-codegen/src/main/resources/go/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} package {{packageName}} import ( diff --git a/modules/swagger-codegen/src/main/resources/go/model.mustache b/modules/swagger-codegen/src/main/resources/go/model.mustache index fd799a0e35d..7cc53fabbce 100644 --- a/modules/swagger-codegen/src/main/resources/go/model.mustache +++ b/modules/swagger-codegen/src/main/resources/go/model.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} package {{packageName}} {{#models}}{{#imports}} import ({{/imports}}{{#imports}} diff --git a/modules/swagger-codegen/src/main/resources/go/partial_header.mustache b/modules/swagger-codegen/src/main/resources/go/partial_header.mustache new file mode 100644 index 00000000000..bf5862deafd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/partial_header.mustache @@ -0,0 +1,25 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * 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. + */ diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 60da5979a89..26f7f564ff5 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -14,10 +14,17 @@ {{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} {{#version}}
Version: {{{version}}}
{{/version}} + {{#basePathWithoutHost}}
BasePath:{{basePathWithoutHost}}
{{/basePathWithoutHost}}
{{{licenseInfo}}}
{{{licenseUrl}}}

Access

- {{access}} + {{#hasAuthMethods}} +
    + {{#authMethods}} +
  1. {{#isBasic}}HTTP Basic Authentication{{/isBasic}}{{#isOAuth}}OAuth AuthorizationUrl:{{authorizationUrl}}TokenUrl:{{tokenUrl}}{{/isOAuth}}{{#isApiKey}}APIKey KeyParamName:{{keyParamName}} KeyInQuery:{{isKeyInQuery}} KeyInHeader:{{isKeyInHeader}}{{/isApiKey}}
  2. + {{/authMethods}} +
+ {{/hasAuthMethods}}

Methods

[ Jump to Models ] @@ -61,7 +68,7 @@ This API call consumes the following media types via the Content-Type request header:
    {{#consumes}} -
  • {{mediaType}}
  • +
  • {{{mediaType}}}
  • {{/consumes}}
{{/hasConsumes}} @@ -118,7 +125,7 @@ the media type will be conveyed by the Content-Type response header.
    {{#produces}} -
  • {{mediaType}}
  • +
  • {{{mediaType}}}
  • {{/produces}}
{{/hasProduces}} @@ -149,7 +156,7 @@
    {{#models}} {{#model}} -
  1. {{classname}}
  2. +
  3. {{name}}
  4. {{/model}} {{/models}}
@@ -157,7 +164,7 @@ {{#models}} {{#model}}
-

{{classname}} Up

+

{{name}} Up

{{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{^isPrimitiveType}}{{datatype}}{{/isPrimitiveType}} {{description}}
{{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/lumen/app/Http/routes.mustache b/modules/swagger-codegen/src/main/resources/lumen/app/Http/routes.mustache index ccef81b0456..de2ed042016 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/app/Http/routes.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/app/Http/routes.mustache @@ -15,7 +15,7 @@ $app->get('/', function () use ($app) { * {{httpMethod}} {{nickname}} * Summary: {{summary}} * Notes: {{notes}} -{{#hasProduces}} * Output-Formats: [{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} +{{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ $app->{{httpMethod}}('{{path}}', function({{#pathParams}}${{paramName}}, {{/pathParams}}$null = null) use ($app) { $input = Request::all(); diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 2d2b917c4b2..5496ee06f80 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -6,7 +6,7 @@ "keywords": [ "swagger" ], - "license": "MIT", + "license": "Apache-2.0", "private": true, "dependencies": { "connect": "^3.2.0", diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 5afc917e228..10cb6528d86 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -2,7 +2,7 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) @interface {{classPrefix}}ApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -50,6 +50,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (instancetype)initWithBaseURL:(NSURL *)url { self = [super initWithBaseURL:url]; if (self) { + self.timeoutInterval = 60; self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [self customSecurityPolicy]; @@ -83,52 +84,13 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) reachabilityStatus = status; } -- (void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey { +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - {{classPrefix}}DebugLog(message); +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + [super setRequestSerializer:requestSerializer]; + requestSerializer.timeoutInterval = self.timeoutInterval; } #pragma mark - Cache Methods @@ -151,86 +113,20 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods -+(unsigned long)requestQueueSize { ++(NSUInteger)requestQueueSize { return [queuedRequests count]; } +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - {{classPrefix}}DebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +190,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +217,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return; } strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -330,8 +226,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); } - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); NSString * filename = {{classPrefix}}__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; @@ -370,14 +265,14 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -386,15 +281,18 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; formParams = [self.sanitizer sanitizeForSerialization:formParams]; - body = [self.sanitizer sanitizeForSerialization:body]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[{{classPrefix}}ApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -438,10 +336,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -462,9 +357,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -485,59 +378,66 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -549,24 +449,26 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { - if (!authSettings || [authSettings count] == 0) { + if ([authSettings count] == 0) { return; } NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = configurationAuthSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } @@ -577,7 +479,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + {{classPrefix}}Configuration *config = [self configuration]; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; @@ -595,4 +497,8 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return securityPolicy; } +- ({{classPrefix}}Configuration*) configuration { + return [{{classPrefix}}Configuration sharedConfig]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index b08112ba445..be5eba32ee0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -1,17 +1,15 @@ #import #import -#import +#import #import "{{classPrefix}}JSONResponseSerializer.h" #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +#import "{{classPrefix}}Logger.h" + +{{>licenceInfo}} {{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} @@ -26,13 +24,6 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef {{classPrefix}}DebugLog - #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -62,7 +53,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @return The size of `queuedRequests` static variable. */ -+(unsigned long)requestQueueSize; ++(NSUInteger)requestQueueSize; /** * Sets the client unreachable @@ -113,15 +104,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -134,24 +116,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -172,19 +136,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -223,8 +174,11 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - (AFSecurityPolicy *) customSecurityPolicy; /** - * Log debug message + * {{classPrefix}}Configuration return sharedConfig + * + * @return {{classPrefix}}Configuration */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; +- ({{classPrefix}}Configuration*) configuration; + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 527e16c2b91..1aeca25dd3e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -2,14 +2,15 @@ @interface {{classPrefix}}Configuration () -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; +@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; @end @implementation {{classPrefix}}Configuration -#pragma mark - Singletion Methods +#pragma mark - Singleton Methods + (instancetype) sharedConfig { static {{classPrefix}}Configuration *shardConfig = nil; @@ -30,12 +31,12 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; + self.logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -43,11 +44,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +73,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +96,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -154,4 +142,34 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index b77ddfe5dee..e727942a4f2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,17 +1,18 @@ #import #import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}Logger.h" -/** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} @class {{classPrefix}}ApiClient; @interface {{classPrefix}}Configuration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + /** * Default api client */ @@ -37,7 +38,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +57,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -113,8 +100,6 @@ /** * Sets the prefix for API key * - * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. - * * @param apiKeyPrefix API key prefix. * @param identifier API key identifier. */ @@ -143,8 +128,33 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache index 78b1409b6b9..63513335d9a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache @@ -17,19 +17,21 @@ withParameters:(id)parameters error:(NSError *__autoreleasing *)error { + if (!parameters) { + return request; + } // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } else { - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - if (parameters) { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; } @end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-header.mustache index a0732b93706..1259c5d1530 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-header.mustache @@ -1,5 +1,7 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer @end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache index 3a19dd1ca4e..7fa5e7b19e0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache @@ -1,13 +1,5 @@ #import "{{classPrefix}}JSONResponseSerializer.h" -static BOOL JSONParseError(NSError *error) { - if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { - return YES; - } - - return NO; -} - @implementation {{classPrefix}}JSONResponseSerializer /// @@ -17,7 +9,7 @@ static BOOL JSONParseError(NSError *error) { /// /// @param response The response to be processed. /// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the respnse data. +/// @param error The error that occurred while attempting to decode the response data. /// /// @return The object decoded from the specified response data. /// @@ -27,7 +19,7 @@ static BOOL JSONParseError(NSError *error) { NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; // if response data is not a valid json, return string of data. - if (JSONParseError(*error)) { + if ([self isParseError:*error]) { *error = nil; NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return responseString; @@ -36,4 +28,12 @@ static BOOL JSONParseError(NSError *error) { return responseJson; } +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache index 7a5f152e271..360e4f9cdc5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache @@ -1,6 +1,8 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer @end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m rename to modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache similarity index 88% rename from modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h rename to modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache index 832f485f4f0..2a8d5b0c9e7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache @@ -2,5 +2,8 @@ #import #import +{{>licenceInfo}} + @interface JSONValueTransformer (ISO8601) + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache new file mode 100644 index 00000000000..9a8f7de2418 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache @@ -0,0 +1,74 @@ +#import "{{classPrefix}}Logger.h" + +@interface {{classPrefix}}Logger () + +@end + +@implementation {{classPrefix}}Logger + ++ (instancetype) sharedLogger { + static {{classPrefix}}Logger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + {{classPrefix}}DebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache new file mode 100644 index 00000000000..37afea41a09 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache @@ -0,0 +1,50 @@ +#import + +{{>licenceInfo}} + +#ifndef {{classPrefix}}DebugLogResponse +#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef {{classPrefix}}DebugLog +#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface {{classPrefix}}Logger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Model.xcdatamodel.mustache b/modules/swagger-codegen/src/main/resources/objc/Model.xcdatamodel.mustache new file mode 100644 index 00000000000..bc391cbd0ad --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Model.xcdatamodel.mustache @@ -0,0 +1,9 @@ + + + + {{#models}}{{#model}} +{{#vars}}{{#complexType}} {{/complexType}}{{^complexType}} {{/complexType}} +{{/vars}} + + {{/model}}{{/models}} + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-body.mustache b/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-body.mustache new file mode 100644 index 00000000000..c8e563e75e8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-body.mustache @@ -0,0 +1,18 @@ +{{#models}} +{{#model}} +#import "{{classname}}ManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation {{classname}}ManagedObject + +{{#vars}} +@dynamic {{name}}; +{{/vars}} + +{{/model}} +@end +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-header.mustache b/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-header.mustache new file mode 100644 index 00000000000..e25dad5795c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/NSManagedObject-header.mustache @@ -0,0 +1,35 @@ +#import +#import + +{{>licenceInfo}} + +{{#imports}}#import "{{import}}ManagedObject.h" +{{/imports}} +{{newline}} +{{#models}} +{{#model}} + +NS_ASSUME_NONNULL_BEGIN + +@interface {{classname}}ManagedObject : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}NSManagedObject{{/parent}} + +{{#vars}} +{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} +@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{{complexType}}}ManagedObject*{{/isListContainer}}{{/complexType}} {{name}}; +{{/vars}} + +@end + +@interface {{classname}}ManagedObject (GeneratedAccessors) + +{{#vars}}{{#isListContainer}}{{#complexType}}- (void)add{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; +- (void)remove{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; +- (void)add{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; +- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; +{{/complexType}}{{/isListContainer}}{{/vars}} +@end +{{/model}} +{{/models}} + +NS_ASSUME_NONNULL_END diff --git a/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-body.mustache b/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-body.mustache new file mode 100644 index 00000000000..70f97418eed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-body.mustache @@ -0,0 +1,76 @@ + +{{#models}}{{#model}} +#import "{{classname}}ManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation {{classname}}ManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { +{{#vars}}{{#complexType}} _{{name}}Builder = [[{{complexType}}ManagedObjectBuilder alloc] init]; +{{/complexType}}{{/vars}} } + return self; +} + +-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context { + {{classname}}ManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([{{classname}}ManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*){{name}} context:(NSManagedObjectContext*)context { + {{classname}}ManagedObject* new{{classname}} = [self createNew{{{classname}}}ManagedObjectInContext:context]; + [self update{{classname}}ManagedObject:new{{classname}} with{{classname}}:{{name}}]; + return new{{classname}}; +} + +-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)managedObject with{{classname}}:({{classname}}*)object { + if(!managedObject || !object) { + return; + } +{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(object.{{name}}) { + NSMutableSet * convertedObjs = [NSMutableSet set]; + for (id innerObject in object.{{name}}) { + id convertedObj = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:innerObject context:managedObject.managedObjectContext]; + [convertedObjs addObject:convertedObj]; + } + managedObject.{{name}} = convertedObjs; + }{{/isListContainer}}{{^isListContainer}} + if(!managedObject.{{name}}) { + managedObject.{{name}} = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:object.{{name}} context:managedObject.managedObjectContext]; + } else { + [self.{{name}}Builder update{{complexType}}ManagedObject:managedObject.{{name}} with{{complexType}}:object.{{name}}]; + }{{/isListContainer}}{{/complexType}} + {{/vars}} +} + +-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { + if(!obj) { + return nil; + } + {{classname}}* new{{classname}} = [[{{classname}} alloc] init]; + [self update{{classname}}:new{{classname}} with{{classname}}ManagedObject:obj]; + return new{{classname}}; +} + +-(void)update{{classname}}:({{classname}}*)new{{classname}} with{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { +{{#vars}}{{^complexType}} new{{classname}}.{{name}} = [obj.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(obj.{{name}} != nil) { + NSMutableArray* convertedObjs = [NSMutableArray array]; + for (id innerObject in obj.{{name}}) { + id convertedObj = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:innerObject]; + [convertedObjs addObject:convertedObj]; + } + new{{classname}}.{{name}} = ({{{ datatype }}})convertedObjs; + } + {{/isListContainer}}{{^isListContainer}} new{{classname}}.{{name}} = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:obj.{{name}}];{{/isListContainer}}{{/complexType}} + {{/vars}} +} + +@end +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-header.mustache b/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-header.mustache new file mode 100644 index 00000000000..f462a1f0950 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/NSManagedObjectBuilder-header.mustache @@ -0,0 +1,31 @@ +#import +#import + +{{#imports}}#import "{{import}}ManagedObjectBuilder.h" +{{/imports}} +{{#models}} +{{#model}} + +#import "{{classPrefix}}{{name}}ManagedObject.h" +#import "{{classPrefix}}{{name}}.h" + +{{>licenceInfo}} + +@interface {{classname}}ManagedObjectBuilder : NSObject + +{{#vars}}{{#complexType}}@property (nonatomic, strong) {{complexType}}ManagedObjectBuilder * {{name}}Builder; +{{/complexType}}{{/vars}} + +-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context; + +-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*){{name}} context:(NSManagedObjectContext*)context; + +-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*){{name}} with{{classname}}:({{classname}}*){{name}}2; + +-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj; + +-(void)update{{classname}}:({{classname}}*){{name}} with{{classname}}ManagedObject:({{classname}}ManagedObject*){{name}}2; + +@end +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-header.mustache index d96e379908f..89da6a4d8b6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-header.mustache @@ -1,5 +1,8 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}Object : JSONModel + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-header.mustache b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-header.mustache index 0389cce98be..9729c182bd8 100644 --- a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-header.mustache @@ -1,5 +1,7 @@ #import +{{>licenceInfo}} + @interface {{classPrefix}}QueryParamCollection : NSObject @property(nonatomic, readonly) NSArray* values; diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index ed48e239596..db56c1b4b77 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -42,6 +42,7 @@ pod '{{podName}}', :path => 'Vendor/{{podName}}' ### Usage Import the following: + ```objc #import <{{podName}}/{{{classPrefix}}}ApiClient.h> #import <{{podName}}/{{{classPrefix}}}Configuration.h> @@ -81,12 +82,10 @@ Please follow the [installation procedure](#installation--usage) and then run th {{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} -@try -{ - {{classname}} *apiInstance = [[{{classname}} alloc] init]; +{{classname}} *apiInstance = [[{{classname}} alloc] init]; {{#summary}} // {{{.}}} -{{/summary}} [apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) { {{#returnType}} @@ -98,12 +97,6 @@ Please follow the [installation procedure](#installation--usage) and then run th NSLog(@"Error: %@", error); } }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache index 2dd038c13f0..90aa174d7c4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache @@ -1,10 +1,6 @@ #import -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} /** * A key for deserialization ErrorDomain diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache index 74b166d75e9..00d74aaa1f7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -3,12 +3,58 @@ #import "{{classPrefix}}QueryParamCollection.h" #import +NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { + static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + @interface {{classPrefix}}Sanitizer () +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + @end @implementation {{classPrefix}}Sanitizer +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + - (id) sanitizeForSerialization:(id) object { if (object == nil) { return nil; @@ -17,7 +63,7 @@ return object; } else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; + return [self dateParameterToString:object]; } else if ([object isKindOfClass:[NSArray class]]) { NSArray *objectArray = object; @@ -61,7 +107,7 @@ return [param stringValue]; } else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; + return [self dateParameterToString:param]; } else if ([param isKindOfClass:[NSArray class]]) { NSMutableArray *mutableParam = [NSMutableArray array]; @@ -79,4 +125,44 @@ } } +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache index 706a94c1d0e..f975018a020 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache @@ -1,10 +1,8 @@ #import -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} + +extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); @protocol {{classPrefix}}Sanitizer @@ -20,6 +18,24 @@ */ - (NSString *) parameterToString: (id) param; +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + @end @interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 2a7880d8367..57fdc4ae6a7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -6,24 +6,29 @@ {{newline}} @interface {{classname}} () - @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; + +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; + @end @implementation {{classname}} -static {{classname}}* singletonAPI = nil; +NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; +NSInteger k{{classname}}MissingParamErrorCode = 234513; + +@synthesize apiClient = _apiClient; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; if (config.apiClient == nil) { config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; } - self.apiClient = config.apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } @@ -31,39 +36,36 @@ static {{classname}}* singletonAPI = nil; - (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { - self.apiClient = apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { - singletonAPI = [[{{classname}} alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; ++ (instancetype)sharedAPI { + static {{classname}} *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; } -+({{classname}}*) sharedAPI { - if (singletonAPI == nil) { - singletonAPI = [[{{classname}} alloc] init]; - } - return singletonAPI; +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; } -(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - --(unsigned long) requestQueueSize { +-(NSUInteger) requestQueueSize { return [{{classPrefix}}ApiClient requestQueueSize]; } @@ -84,7 +86,13 @@ static {{classname}}* singletonAPI = nil; {{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"]; + NSParameterAssert({{paramName}}); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; + NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; + handler({{#returnType}}nil, {{/returnType}}error); + } + return nil; } {{/required}} @@ -92,9 +100,7 @@ static {{classname}}* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; {{#pathParams}} @@ -107,36 +113,29 @@ static {{classname}}* singletonAPI = nil; {{#queryParams}} if ({{paramName}} != nil) { {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; {{#headerParams}} - if ({{paramName}} != nil) { headerParams[@"{{baseName}}"] = {{paramName}}; } - {{/headerParams}} // HTTP header `Accept` - headerParams[@"Accept"] = [{{classPrefix}}ApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [{{classPrefix}}ApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; @@ -173,7 +172,9 @@ static {{classname}}* singletonAPI = nil; responseContentType: responseContentType responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} completionBlock: ^(id data, NSError *error) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } } ]; } diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 7c5a9d335cf..abe4cf64eb0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -1,34 +1,26 @@ #import {{#imports}}#import "{{import}}.h" {{/imports}} -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiClient.h" -{{newline}} +#import "{{classPrefix}}Api.h" -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} + + +@interface {{classname}}: NSObject <{{classPrefix}}Api> + +extern NSString* k{{classname}}ErrorDomain; +extern NSInteger k{{classname}}MissingParamErrorCode; + ++(instancetype) sharedAPI; {{#operations}} -@interface {{classname}}: NSObject - -@property(nonatomic, assign){{classPrefix}}ApiClient *apiClient; - --(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; --(void) addHeader:(NSString*)value forKey:(NSString*)key; --(unsigned long) requestQueueSize; -+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+({{classname}}*) sharedAPI; {{#operation}} -/// -/// /// {{{summary}}} /// {{#notes}}{{{notes}}}{{/notes}} /// /// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} -(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} @@ -37,6 +29,6 @@ {{newline}} {{/operation}} - {{/operations}} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache new file mode 100644 index 00000000000..da87a712fa2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache @@ -0,0 +1,20 @@ +#import +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}ApiClient.h" + +{{>licenceInfo}} + +@protocol {{classPrefix}}Api + +@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient; + +-(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; + +-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; +-(NSString*) defaultHeaderForKey:(NSString*)key; + +-(NSUInteger) requestQueueSize; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache index c27f6425388..44fe31d6404 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache @@ -42,29 +42,21 @@ Method | HTTP request | Description {{#allParams}}{{{dataType}}} {{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} -@try -{ - {{classname}} *apiInstance = [[{{classname}} alloc] init]; +{{classname}}*apiInstance = [[{{classname}} alloc] init]; -{{#summary}} // {{{.}}} -{{/summary}} [apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { {{#returnType}} - if (output) { - NSLog(@"%@", output); - } + if (output) { + NSLog(@"%@", output); + } {{/returnType}} - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} + if (error) { + NSLog(@"Error calling {{classname}}->{{operationId}}: %@", error); + } + }]; ``` ### Parameters @@ -84,8 +76,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache old mode 100755 new mode 100644 diff --git a/modules/swagger-codegen/src/main/resources/objc/licenceInfo.mustache b/modules/swagger-codegen/src/main/resources/objc/licenceInfo.mustache new file mode 100644 index 00000000000..2f0f1940e89 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/licenceInfo.mustache @@ -0,0 +1,23 @@ +/** +* {{{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. +* +* 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. +*/ \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 776cd55ccef..ae4e66fba69 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -7,7 +7,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; {{/defaultValue}}{{/vars}} } @@ -16,25 +16,18 @@ {{#discriminator}} /** - Maps "discriminator" value to the sub-class name, so that inheritance is supported. + * Maps "discriminator" value to the sub-class name, so that inheritance is supported. */ - (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { - NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; - if(discriminatedClassName == nil ){ return [super initWithDictionary:dict error:err]; } - Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); - if([self class ] == class) { return [super initWithDictionary:dict error:err]; } - - return [[class alloc] initWithDictionary:dict error: err]; - } {{/discriminator}} @@ -55,7 +48,6 @@ NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; return [optionalProperties containsObject:propertyName]; - } {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index f9a33042491..04570e71a2f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -1,11 +1,7 @@ #import #import "{{classPrefix}}Object.h" -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} {{#imports}}#import "{{import}}.h" {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 338ded84e89..bd0bd9f328e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -13,24 +13,25 @@ Pod::Spec.new do |s| {{#apiInfo}}{{#apis}}{{^hasMore}} s.summary = "{{appName}}" s.description = <<-DESC - {{appDescription}} + {{{appDescription}}} DESC {{/hasMore}}{{/apis}}{{/apiInfo}} s.platform = :ios, '7.0' s.requires_arc = true - s.framework = 'SystemConfiguration' - + {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} + s.homepage = "{{gitRepoURL}}" - s.license = "{{license}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } s.author = { "{{authorName}}" => "{{authorEmail}}" } - s.source_files = '{{podName}}/**/*' + s.source_files = '{{podName}}/**/*.{m,h}' s.public_header_files = '{{podName}}/**/*.h' +{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/modules/swagger-codegen/src/main/resources/objc/xccurrentversion.mustache b/modules/swagger-codegen/src/main/resources/objc/xccurrentversion.mustache new file mode 100644 index 00000000000..528b389e3ef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/xccurrentversion.mustache @@ -0,0 +1,8 @@ + + + + + _XCCurrentVersionName + {{classPrefix}}Model.xcdatamodel + + diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 401a33eddad..4da9f8fb41e 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 {{moduleName}}::ApiClient; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache index ef5f322a014..cbda8660c20 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 {{moduleName}}::ApiFactory; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache index 3c10c2450fe..2d5eb5208cf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 {{moduleName}}::Role::AutoDoc; use List::MoreUtils qw(uniq); diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 9f262543acd..80ecda42a4d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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' => {}); diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index e0ed9bf3295..500d816b178 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 {{moduleName}}::Configuration; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index fb343ccb890..0c8c1a0375b 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 {{moduleName}}::Role; use utf8; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index d96a2302a8a..3ac7f435908 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -1,21 +1,8 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +{{>partial_license}} # # 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 {{moduleName}}::{{classname}}; @@ -100,11 +87,11 @@ sub {{operationId}} { my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); + my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); {{#queryParams}} # query params diff --git a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache index 17dc3903152..585a67c1ac1 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache @@ -67,8 +67,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/perl/api_test.mustache b/modules/swagger-codegen/src/main/resources/perl/api_test.mustache index 98d1e9cce99..6ae0a8b286a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_test.mustache @@ -1,21 +1,8 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +{{>partial_license}} # # NOTE: This class is auto generated by Swagger Codegen -# Please update the test case below to test the API endpoints. +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen # use Test::More tests => 1; #TODO update number of test cases use Test::Exception; diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index 126c6409c7f..bb19479c61d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# 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 +# {{#models}} {{#model}} package {{moduleName}}::Object::{{classname}}; @@ -19,7 +25,8 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #{{description}} # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# 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 # {{>BaseObject}} diff --git a/modules/swagger-codegen/src/main/resources/perl/object_test.mustache b/modules/swagger-codegen/src/main/resources/perl/object_test.mustache index dd76f9ac2d7..08ea9200a0a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object_test.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object_test.mustache @@ -1,6 +1,9 @@ +{{>partial_license}} +# # NOTE: This class is auto generated by the Swagger Codegen -# Please update the test case below to test the model. - +# 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; diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5b8b9b21632..98a6ad5df8c 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -10,21 +10,8 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + +{{>partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -55,18 +42,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\{{invokerPackage}}\Configuration $config = null) @@ -81,6 +71,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +81,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +91,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +116,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ @@ -160,7 +156,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -171,7 +167,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -202,7 +198,7 @@ class ApiClient // debugging for curl if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); + error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); @@ -216,19 +212,19 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); // debug HTTP response body if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); + error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); } // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -246,7 +242,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -295,40 +293,35 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - - foreach(explode("\n", $raw_headers) as $h) - { + + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } else { + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } - + return $headers; } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index eee688001ed..2cffdea5ccf 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -9,21 +9,8 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + +{{>partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -48,30 +35,34 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -100,7 +91,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/modules/swagger-codegen/src/main/resources/php/LICENSE b/modules/swagger-codegen/src/main/resources/php/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 34d79b0ae39..4f99eaac4c3 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -1,6 +1,6 @@ partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -37,7 +24,7 @@ namespace {{invokerPackage}}; * ObjectSerializer Class Doc Comment * * @category Class - * @package {{invokerPackage}} + * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen @@ -79,7 +66,7 @@ class ObjectSerializer /** * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif + * e.g. ../../sun.gif becomes sun.gif * * @param string $filename filename to be sanitized * @@ -185,7 +172,7 @@ class ObjectSerializer * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti=false) + public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just @@ -219,7 +206,7 @@ class ObjectSerializer * * @return object an instance of $class */ - public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) + public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { if (null === $data) { return null; @@ -261,16 +248,20 @@ class ObjectSerializer return $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && + preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - return $deserialized; + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + + return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +273,11 @@ class ObjectSerializer $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, $discriminator)); diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index 3049d013ca5..4186ed0ea99 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -6,7 +6,9 @@ This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: {{appVersion}} +{{#artifactVersion}} - Package version: {{artifactVersion}} +{{/artifactVersion}} - Build date: {{generatedDate}} - Build package: {{generatorClass}} {{#infoUrl}} @@ -27,11 +29,11 @@ To install the bindings via [Composer](http://getcomposer.org/), add the followi "repositories": [ { "type": "git", - "url": "https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}.git" + "url": "https://github.com/{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}.git" } ], "require": { - "{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}": "*@dev" + "{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}": "*@dev" } } ``` @@ -46,7 +48,7 @@ Download the files and include `autoload.php`: require_once('/path/to/{{packagePath}}/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -82,7 +84,7 @@ try { {{#returnType}}$result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { - echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), "\n"; + echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; } {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ?> @@ -108,7 +110,7 @@ Class | Method | HTTP request | Description {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}}- **Type**: API key - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index cc74dfd3a2a..26f79cd6139 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -9,25 +9,11 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +{{>partial_header}} /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +38,41 @@ use \{{invokerPackage}}\ObjectSerializer; /** * API Client + * * @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use */ - function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) + public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \{{invokerPackage}}\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * * @return {{classname}} */ public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) @@ -89,31 +80,33 @@ use \{{invokerPackage}}\ObjectSerializer; $this->apiClient = $apiClient; return $this; } - + {{#operation}} /** - * {{{operationId}}} + * Operation {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{/allParams}} * + * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - list($response) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - return $response; + list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + return $response; } /** - * {{{operationId}}}WithHttpInfo + * Operation {{{operationId}}}WithHttpInfo * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) + {{/allParams}} * + * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -153,19 +146,19 @@ use \{{invokerPackage}}\ObjectSerializer; {{/hasValidation}} {{/allParams}} - + // parse inputs $resourcePath = "{{path}}"; $httpBody = ''; $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); - + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{{mediaType}}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + {{#queryParams}}// query params {{#collectionFormat}} if (is_array(${{paramName}})) { @@ -208,7 +201,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (function_exists('curl_file_create')) { $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); } else { - $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); } {{/isFile}} {{^isFile}} @@ -220,7 +213,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (isset(${{paramName}})) { $_tempBody = ${{paramName}}; }{{/bodyParams}} - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -244,9 +237,12 @@ use \{{invokerPackage}}\ObjectSerializer; // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, '{{httpMethod}}', - $queryParams, $httpBody, - $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} + $resourcePath, + '{{httpMethod}}', + $queryParams, + $httpBody, + $headerParams{{#returnType}}, + '{{returnType}}'{{/returnType}} ); {{#returnType}} if (!$response) { @@ -254,17 +250,22 @@ use \{{invokerPackage}}\ObjectSerializer; } return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); - {{/returnType}}{{^returnType}} + {{/returnType}} + {{^returnType}} return array(null, $statusCode, $httpHeader); {{/returnType}} } catch (ApiException $e) { - switch ($e->getCode()) { {{#responses}}{{#dataType}} - {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); - $e->setResponseObject($data); - break;{{/dataType}}{{/responses}} + switch ($e->getCode()) { + {{#responses}} + {{#dataType}} + {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + {{/dataType}} + {{/responses}} } - + throw $e; } } diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache index 4cf01aa510b..75ec5f8acd8 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -17,7 +17,7 @@ Method | HTTP request | Description {{{notes}}}{{/notes}} -### Example +### Example ```php {{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { - echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), "\n"; + echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -50,7 +50,7 @@ try { {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**](../Model/{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**](../Model/{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}} {{/allParams}} ### Return type @@ -63,8 +63,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index fc07d338301..c53cd6e1ad2 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -9,25 +9,11 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +{{>partial_header}} /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,14 +39,16 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } @@ -68,10 +56,11 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Test case for {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * */ - public function test_{{operationId}}() { + public function test{{vendorExtensions.x-testOperationId}}() + { } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 04be6e11992..28ce32ae50a 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -1,14 +1,17 @@ partial_header}} /** * An example of a project-specific implementation. - * + * * After registering this autoload function with SPL, the following line * would cause the function to attempt to load the \{{invokerPackage}}\Baz\Qux class * from /path/to/project/{{srcBasePath}}/Baz/Qux.php: - * + * * new \{{invokerPackage}}\Baz\Qux; - * + * * @param string $class The fully-qualified class name. + * * @return void */ spl_autoload_register(function ($class) { diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 062a3ddc6cc..477e0819324 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -1,6 +1,8 @@ { - "name": "{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}",{{#artifactVersion}} - "version": "{{artifactVersion}}",{{/artifactVersion}} + "name": "{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}", + {{#artifactVersion}} + "version": "{{artifactVersion}}", + {{/artifactVersion}} "description": "{{description}}", "keywords": [ "swagger", diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 0062fa8c25f..7e3883cf9c4 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -10,22 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - +{{>partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -47,7 +32,7 @@ namespace {{invokerPackage}}; class Configuration { - private static $_defaultConfiguration = null; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -110,7 +95,7 @@ class Configuration * * @var string */ - protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/php{{/httpUserAgent}}"; + protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}"; /** * Debug switch (default set to false) @@ -487,11 +472,11 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$_defaultConfiguration == null) { - self::$_defaultConfiguration = new Configuration(); + if (self::$defaultConfiguration == null) { + self::$defaultConfiguration = new Configuration(); } - return self::$_defaultConfiguration; + return self::$defaultConfiguration; } /** @@ -503,7 +488,7 @@ class Configuration */ public static function setDefaultConfiguration(Configuration $config) { - self::$_defaultConfiguration = $config; + self::$defaultConfiguration = $config; } /** @@ -513,14 +498,15 @@ class Configuration */ public static function toDebugReport() { - $report = "PHP SDK ({{invokerPackage}}) Debug Report:\n"; - $report .= " OS: ".php_uname()."\n"; - $report .= " PHP Version: ".phpversion()."\n"; - $report .= " OpenAPI Spec Version: {{version}}\n"; - $report .= " SDK Package Version: {{artifactVersion}}\n"; - $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; + $report = 'PHP SDK ({{invokerPackage}}) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . phpversion() . PHP_EOL; + $report .= ' OpenAPI Spec Version: {{version}}' . PHP_EOL; + {{#artifactVersion}} + $report .= ' SDK Package Version: {{artifactVersion}}' . PHP_EOL; + {{/artifactVersion}} + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; } - } diff --git a/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache index e153ce23ecf..a9b0f28edfb 100755 --- a/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/php/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/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 6dbf2544a17..9fc2b620ddd 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -12,21 +12,8 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + +{{>partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -41,7 +28,9 @@ use \ArrayAccess; * {{classname}} Class Doc Comment * * @category Class +{{#description}} * @description {{description}} +{{/description}} * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -53,31 +42,33 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * The original name of the model. * @var string */ - static $swaggerModelName = '{{name}}'; + protected static $swaggerModelName = '{{name}}'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}}; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function attributeMap() { + public static function attributeMap() + { return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; } @@ -85,12 +76,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function setters() { + public static function setters() + { return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; } @@ -98,12 +90,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function getters() { + + public static function getters() + { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } @@ -115,7 +108,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} @@ -152,48 +146,48 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { - $invalid_properties[] = "'${{name}}' can't be null"; + $invalid_properties[] = "'{{name}}' can't be null"; } {{/required}} {{#isEnum}} $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); if (!in_array($this->container['{{name}}'], $allowed_values)) { - $invalid_properties[] = "invalid value for '${{name}}', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for '{{name}}', must be one of #{allowed_values}."; } {{/isEnum}} {{#hasValidation}} {{#maxLength}} if (strlen($this->container['{{name}}']) > {{maxLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; } {{/maxLength}} {{#minLength}} if (strlen($this->container['{{name}}']) < {{minLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be bigger than or equal to {{{minLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; } {{/minLength}} {{#maximum}} if ($this->container['{{name}}'] > {{maximum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be smaller than or equal to {{maximum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be smaller than or equal to {{maximum}}."; } {{/maximum}} {{#minimum}} if ($this->container['{{name}}'] < {{minimum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be bigger than or equal to {{minimum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be bigger than or equal to {{minimum}}."; } {{/minimum}} {{#pattern}} if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { - $invalid_properties[] = "invalid value for '${{name}}', must be conform to the pattern {{pattern}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{pattern}}."; } {{/pattern}} {{/hasValidation}} @@ -204,8 +198,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -265,7 +259,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Sets {{name}} - * @param {{datatype}} ${{name}} {{#description}}{{{description}}}{{/description}} + * @param {{datatype}} ${{name}}{{#description}} {{{description}}}{{/description}} * @return $this */ public function {{setter}}(${{name}}) @@ -309,7 +303,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -319,17 +313,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -341,17 +335,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache index 4598f9fdff9..ffb268c6cb9 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache @@ -7,7 +7,8 @@ class {{classname}} { * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 006cd09c62a..22f97456e04 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -1,19 +1,20 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayAccess { /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function swaggerTypes() { + + static function swaggerTypes() + { return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -21,8 +22,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function attributeMap() { + + static function attributeMap() + { return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; } @@ -34,8 +36,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function setters() { + + static function setters() + { return {{#parent}}parent::setters() + {{/parent}}self::$setters; } @@ -47,8 +50,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function getters() { + + static function getters() + { return {{#parent}}parent::getters() + {{/parent}}self::$getters; } @@ -60,7 +64,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} @@ -115,7 +120,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -125,17 +130,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return $this->$offset; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -143,17 +148,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA { $this->$offset = $value; } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->$offset); } - + /** * Gets the string presentation of the object. * @return string diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index 0d615eca102..d7d93f32186 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -12,21 +12,8 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -/** - * Copyright 2016 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + +{{>partial_header}} /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +26,7 @@ namespace {{modelPackage}}; * {{classname}}Test Class Doc Comment * * @category Class - * @description {{description}} + * @description {{#description}}{{description}}{{/description}}{{^description}}{{classname}}{{/description}} * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,24 +38,26 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test {{classname}} + * Test "{{classname}}" */ - public function test{{classname}}() { + public function test{{classname}}() + { } - } {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/php/partial_header.mustache b/modules/swagger-codegen/src/main/resources/php/partial_header.mustache new file mode 100644 index 00000000000..61098d84563 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/partial_header.mustache @@ -0,0 +1,25 @@ +/** + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * 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. + */ diff --git a/modules/swagger-codegen/src/main/resources/python/LICENSE b/modules/swagger-codegen/src/main/resources/python/LICENSE new file mode 100644 index 00000000000..9c8f3ea0871 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache index da086c10873..1a9eaf62794 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,3 +1,7 @@ +# coding: utf-8 + +{{>partial_header}} + from __future__ import absolute_import # import models into model package diff --git a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache index 5265587cfd9..6528c480eed 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -1,3 +1,7 @@ +# coding: utf-8 + +{{>partial_header}} + from __future__ import absolute_import # import models into sdk package diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 94458e3f724..050278b2b5d 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -1,21 +1,6 @@ # coding: utf-8 -""" -{{classname}}.py -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" +{{>partial_header}} from __future__ import absolute_import @@ -88,7 +73,6 @@ class {{classname}}(object): ) params[key] = val del params['kwargs'] - {{#allParams}} {{#required}} # verify the required parameter '{{paramName}}' is set @@ -100,28 +84,27 @@ class {{classname}}(object): {{#allParams}} {{#hasValidation}} {{#maxLength}} - if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxLength}}: + if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxLength}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than or equal to `{{maxLength}}`") {{/maxLength}} {{#minLength}} - if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minLength}}: + if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minLength}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: + if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than or equal to `{{maximum}}`") {{/maximum}} {{#minimum}} - if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: + if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if '{{paramName}}' in params and not re.search('{{vendorExtensions.x-regex}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + if '{{paramName}}' in params and not re.search('{{vendorExtensions.x-regex}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") {{/pattern}} {{/hasValidation}} {{/allParams}} - resource_path = '{{path}}'.replace('{format}', 'json') path_params = {} {{#pathParams}} @@ -156,13 +139,13 @@ class {{classname}}(object): # HTTP header `Accept` header_params['Accept'] = self.api_client.\ - select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + select_header_accept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ - select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + select_header_content_type([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) # Authentication setting auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 07b9419e08f..2a4732f5afd 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -191,7 +191,7 @@ class ApiClient(object): :return: The serialized form of data. """ types = (str, int, float, bool, tuple) - if sys.version_info < (3,0): + if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): return None diff --git a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache index 8eb25a87b06..98dec04a393 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -65,8 +65,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} [[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/modules/swagger-codegen/src/main/resources/python/api_test.mustache b/modules/swagger-codegen/src/main/resources/python/api_test.mustache index 5f0b0ab6ecb..f0f07f7189e 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_test.mustache @@ -1,22 +1,6 @@ # coding: utf-8 -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ref: https://github.com/swagger-api/swagger-codegen -""" +{{>partial_header}} from __future__ import absolute_import @@ -24,16 +8,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.{{classVarName}} import {{classname}} +import {{packageName}} +from {{packageName}}.rest import ApiException +from {{packageName}}.apis.{{classVarName}} import {{classname}} class {{#operations}}Test{{classname}}(unittest.TestCase): """ {{classname}} unit test stubs """ def setUp(self): - self.api = swagger_client.apis.{{classVarName}}.{{classname}}() + self.api = {{packageName}}.apis.{{classVarName}}.{{classname}}() def tearDown(self): pass @@ -51,4 +35,4 @@ class {{#operations}}Test{{classname}}(unittest.TestCase): {{/operations}} if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 8f878f82318..3d2e8db228b 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,22 +1,6 @@ # coding: utf-8 -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ref: https://github.com/swagger-api/swagger-codegen -""" +{{>partial_header}} from __future__ import absolute_import import base64 @@ -33,6 +17,7 @@ import logging from six import iteritems + def singleton(cls, *args, **kw): instances = {} @@ -75,7 +60,6 @@ class Configuration(object): # access token for OAuth self.access_token = "" {{/isOAuth}}{{/authMethods}} - # Logging Settings self.logger = {} self.logger["package_logger"] = logging.getLogger("{{packageName}}") @@ -235,7 +219,7 @@ class Configuration(object): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, -{{/isBasic}}{{#isOauth}} +{{/isBasic}}{{#isOAuth}} '{{name}}': { 'type': 'oauth2', @@ -243,7 +227,7 @@ class Configuration(object): 'key': 'Authorization', 'value': 'Bearer ' + self.access_token }, -{{/isOauth}}{{/authMethods}} +{{/isOAuth}}{{/authMethods}} } def to_debug_report(self): diff --git a/modules/swagger-codegen/src/main/resources/python/gitignore.mustache b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache index 1dbc687de01..a655050c263 100644 --- a/modules/swagger-codegen/src/main/resources/python/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache @@ -44,6 +44,8 @@ nosetests.xml coverage.xml *,cover .hypothesis/ +venv/ +.python-version # Translations *.mo diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index e62fa2cbf66..a08595db88a 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -1,22 +1,6 @@ # coding: utf-8 -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - Ref: https://github.com/swagger-api/swagger-codegen -""" +{{>partial_header}} {{#models}} {{#model}} @@ -30,7 +14,7 @@ class {{classname}}(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self{{#readWriteVars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/readWriteVars}}): """ {{classname}} - a model defined in Swagger @@ -49,11 +33,14 @@ class {{classname}}(object): {{/hasMore}}{{/vars}} } -{{#vars}} +{{#readOnlyVars}} self._{{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}} -{{/vars}} - -{{#vars}} +{{/readOnlyVars}} +{{#readWriteVars}} + self._{{name}} = {{name}} +{{/readWriteVars}} +{{#vars}}{{#-first}} +{{/-first}} @property def {{name}}(self): """ @@ -65,6 +52,7 @@ class {{classname}}(object): """ return self._{{name}} +{{^isReadOnly}} @{{name}}.setter def {{name}}(self, {{name}}): """ @@ -74,7 +62,8 @@ class {{classname}}(object): :param {{name}}: The {{name}} of this {{classname}}. :type: {{datatype}} """ - {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] +{{#isEnum}} + allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{name}} not in allowed_values: raise ValueError( "Invalid value for `{{name}}`, must be one of {0}" @@ -87,23 +76,23 @@ class {{classname}}(object): if not {{name}}: raise ValueError("Invalid value for `{{name}}`, must not be `None`") {{#maxLength}} - if len({{name}}) > {{maxLength}}: + if len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") {{/maxLength}} {{#minLength}} - if len({{name}}) < {{minLength}}: + if len({{name}}) < {{minLength}}: raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if {{name}} > {{maximum}}: + if {{name}} > {{maximum}}: raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") {{/maximum}} {{#minimum}} - if {{name}} < {{minimum}}: + if {{name}} < {{minimum}}: raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") {{/pattern}} {{/hasValidation}} @@ -111,6 +100,7 @@ class {{classname}}(object): self._{{name}} = {{name}} +{{/isReadOnly}} {{/vars}} def to_dict(self): """ @@ -161,6 +151,5 @@ class {{classname}}(object): Returns true if both objects are not equal """ return not self == other - {{/model}} -{{/models}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/model_test.mustache b/modules/swagger-codegen/src/main/resources/python/model_test.mustache index c00a10a9b51..9e1b72b14a0 100644 --- a/modules/swagger-codegen/src/main/resources/python/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model_test.mustache @@ -1,22 +1,6 @@ # coding: utf-8 -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ref: https://github.com/swagger-api/swagger-codegen -""" +{{>partial_header}} from __future__ import absolute_import @@ -26,9 +10,9 @@ import unittest {{#models}} {{#model}} -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.{{classFilename}} import {{classname}} +import {{packageName}} +from {{packageName}}.rest import ApiException +from {{packageName}}.models.{{classFilename}} import {{classname}} class Test{{classname}}(unittest.TestCase): @@ -44,10 +28,10 @@ class Test{{classname}}(unittest.TestCase): """ Test {{classname}} """ - model = swagger_client.models.{{classFilename}}.{{classname}}() + model = {{packageName}}.models.{{classFilename}}.{{classname}}() {{/model}} {{/models}} if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/modules/swagger-codegen/src/main/resources/python/partial_header.mustache b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache new file mode 100644 index 00000000000..004460091dd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache @@ -0,0 +1,25 @@ +""" +{{#appName}} + {{{appName}}} +{{/appName}} + +{{#appDescription}} + {{{appDescription}}} +{{/appDescription}} + + {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + 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. +""" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/requirements.mustache b/modules/swagger-codegen/src/main/resources/python/requirements.mustache new file mode 100644 index 00000000000..f00e08fa339 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/requirements.mustache @@ -0,0 +1,5 @@ +certifi >= 14.05.14 +six == 1.8.0 +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.15.1 diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 352bb503ac5..1a6cf193b6c 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,23 +1,7 @@ # coding: utf-8 -""" -Copyright 2016 SmartBear Software +{{>partial_header}} - 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. - -Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: -https://www.dropbox.com/developers/core/sdks/python -""" from __future__ import absolute_import import sys @@ -138,8 +122,11 @@ class RESTClientObject(object): if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': + request_body = None + if body: + request_body = json.dumps(body) r = self.pool_manager.request(method, url, - body=json.dumps(body), + body=request_body, headers=headers) if headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index f95b1f56a0f..f46265995fa 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -1,13 +1,13 @@ # coding: utf-8 +{{>partial_header}} + import sys from setuptools import setup, find_packages NAME = "{{packageName}}" VERSION = "{{packageVersion}}" - {{#apiInfo}}{{#apis}}{{^hasMore}} - # To install the library, run the following # # python setup.py install @@ -31,5 +31,4 @@ setup( {{appDescription}} """ ) - -{{/hasMore}}{{/apis}}{{/apiInfo}} +{{/hasMore}}{{/apis}}{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/test-requirements.mustache b/modules/swagger-codegen/src/main/resources/python/test-requirements.mustache new file mode 100644 index 00000000000..2702246c0e6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/test-requirements.mustache @@ -0,0 +1,5 @@ +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/modules/swagger-codegen/src/main/resources/python/tox.mustache b/modules/swagger-codegen/src/main/resources/python/tox.mustache new file mode 100644 index 00000000000..d99517b76b6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/tox.mustache @@ -0,0 +1,10 @@ +[tox] +envlist = py27, py34 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/rails5/.keep b/modules/swagger-codegen/src/main/resources/rails5/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/404.html b/modules/swagger-codegen/src/main/resources/rails5/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/422.html b/modules/swagger-codegen/src/main/resources/rails5/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/500.html b/modules/swagger-codegen/src/main/resources/rails5/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/Gemfile b/modules/swagger-codegen/src/main/resources/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/modules/swagger-codegen/src/main/resources/rails5/README.md b/modules/swagger-codegen/src/main/resources/rails5/README.md new file mode 100644 index 00000000000..841b82ad656 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create db:migrate +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/modules/swagger-codegen/src/main/resources/rails5/Rakefile b/modules/swagger-codegen/src/main/resources/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/application.rb b/modules/swagger-codegen/src/main/resources/rails5/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_job.rb b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_record.rb b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/modules/swagger-codegen/src/main/resources/rails5/boot.rb b/modules/swagger-codegen/src/main/resources/rails5/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/modules/swagger-codegen/src/main/resources/rails5/bundle b/modules/swagger-codegen/src/main/resources/rails5/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/modules/swagger-codegen/src/main/resources/rails5/cable.yml b/modules/swagger-codegen/src/main/resources/rails5/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/modules/swagger-codegen/src/main/resources/rails5/channel.rb b/modules/swagger-codegen/src/main/resources/rails5/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/config.ru b/modules/swagger-codegen/src/main/resources/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/modules/swagger-codegen/src/main/resources/rails5/connection.rb b/modules/swagger-codegen/src/main/resources/rails5/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/controller.mustache b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache new file mode 100644 index 00000000000..d4c44d54d26 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache @@ -0,0 +1,52 @@ +=begin +{{> info}} +=end +class {{classname}} < ApplicationController +{{#operations}} +{{#operation}} + +{{#isRestfulIndex}} + def index + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulIndex}} +{{#isRestfulShow}} + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulShow}} +{{#isRestfulCreate}} + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulCreate}} +{{#isRestfulUpdate}} + def update + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulUpdate}} +{{#isRestfulDestroy}} + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulDestroy}} +{{^isRestful}} + def {{nickname}} + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestful}} +{{/operation}} +{{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/cors.rb b/modules/swagger-codegen/src/main/resources/rails5/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/database.yml b/modules/swagger-codegen/src/main/resources/rails5/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/development.rb b/modules/swagger-codegen/src/main/resources/rails5/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/en.yml b/modules/swagger-codegen/src/main/resources/rails5/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/modules/swagger-codegen/src/main/resources/rails5/environment.rb b/modules/swagger-codegen/src/main/resources/rails5/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/modules/swagger-codegen/src/main/resources/rails5/favicon.ico b/modules/swagger-codegen/src/main/resources/rails5/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/modules/swagger-codegen/src/main/resources/rails5/inflections.rb b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/info.mustache b/modules/swagger-codegen/src/main/resources/rails5/info.mustache new file mode 100644 index 00000000000..44d38c5cfad --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/info.mustache @@ -0,0 +1,23 @@ +{{#appName}} +{{{appName}}} + +{{/appName}} +{{#appDescription}} +{{{appDescription}}} + +{{/appDescription}} +{{#version}}OpenAPI spec version: {{version}}{{/version}} +{{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +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. diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache new file mode 100644 index 00000000000..508b0ce7ede --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache @@ -0,0 +1,15 @@ +=begin +{{> info}} +=end + +class InitTables < ActiveRecord::Migration + def change{{#models}}{{#model}} + create_table :{{classFilename}}, id: false do |t|{{#vars}}{{#isContainer}} + t.string :{{name}}{{/isContainer}}{{^isContainer}} + t.{{datatype}} :{{{name}}}{{/isContainer}}{{/vars}} + + t.timestamps + end +{{/model}}{{/models}} + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/modules/swagger-codegen/src/main/resources/rails5/model.mustache b/modules/swagger-codegen/src/main/resources/rails5/model.mustache new file mode 100644 index 00000000000..edfe9fac56c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/model.mustache @@ -0,0 +1,12 @@ +=begin +{{> info}} +=end + +{{#models}}{{#model}} +class {{classname}} < ApplicationRecord +{{#requiredVars}} + validate_presence_of :{{name}} +{{/requiredVars}}{{#vars}}{{#isListContainer}} + serialize :{{name}}, Array{{/isListContainer}}{{#isMapContainer}} + serialize :{{name}}, Hash{{/isMapContainer}}{{/vars}} +end{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/rails5/production.rb b/modules/swagger-codegen/src/main/resources/rails5/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/puma.rb b/modules/swagger-codegen/src/main/resources/rails5/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/modules/swagger-codegen/src/main/resources/rails5/rails b/modules/swagger-codegen/src/main/resources/rails5/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/modules/swagger-codegen/src/main/resources/rails5/rake b/modules/swagger-codegen/src/main/resources/rails5/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/modules/swagger-codegen/src/main/resources/rails5/restart.txt b/modules/swagger-codegen/src/main/resources/rails5/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/robots.txt b/modules/swagger-codegen/src/main/resources/rails5/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache new file mode 100644 index 00000000000..76d745d3606 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache @@ -0,0 +1,20 @@ +=begin +{{> info}} +=end +Rails.application.routes.draw do + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method + end + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + add_swagger_route '{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', controller_name: '{{classVarName}}', action_name: {{#isRestfulIndex}}'index'{{/isRestfulIndex}}{{#isRestfulCreate}}'create'{{/isRestfulCreate}}{{#isRestfulUpdate}}'update'{{/isRestfulUpdate}}{{#isRestfulShow}}'show'{{/isRestfulShow}}{{#isRestfulDestroy}}'destroy'{{/isRestfulDestroy}}{{^isRestful}}'{{nickname}}'{{/isRestful}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/schema.rb b/modules/swagger-codegen/src/main/resources/rails5/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/secrets.yml b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/seeds.rb b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/modules/swagger-codegen/src/main/resources/rails5/setup b/modules/swagger-codegen/src/main/resources/rails5/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/spring.rb b/modules/swagger-codegen/src/main/resources/rails5/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/modules/swagger-codegen/src/main/resources/rails5/test.rb b/modules/swagger-codegen/src/main/resources/rails5/test.rb new file mode 100644 index 00000000000..30587ef6d5e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test.rb @@ -0,0 +1,42 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=3600' + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/update b/modules/swagger-codegen/src/main/resources/rails5/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb new file mode 100644 index 00000000000..bbfc3961bff --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/modules/swagger-codegen/src/main/resources/ruby/LICENSE b/modules/swagger-codegen/src/main/resources/ruby/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 20b6d4593e3..5201fd343ea 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -98,11 +98,11 @@ module {{moduleName}} header_params = {} # HTTP header 'Accept' (if needed) - local_header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + local_header_accept = [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - local_header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + local_header_content_type = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache index 1ed497da21e..ae32ff0ccfa 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache @@ -1,3 +1,7 @@ +=begin +{{> api_info}} +=end + require 'spec_helper' describe {{moduleName}}::ApiClient do diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache index a2cee7f9361..02fd5f7f547 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache @@ -22,7 +22,7 @@ Method | HTTP request | Description # load the gem require '{{{gemName}}}' {{#hasAuthMethods}} -# setup authorization +# setup authorization {{{moduleName}}}.configure do |config|{{#authMethods}}{{#isBasic}} # Configure HTTP basic authorization: {{{name}}} config.username = 'YOUR USERNAME' @@ -70,8 +70,8 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_info.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_info.mustache index 28301757e70..44d38c5cfad 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_info.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_info.mustache @@ -1,18 +1,23 @@ -{{#appName}}{{{appName}}} +{{#appName}} +{{{appName}}} {{/appName}} -{{#appDescription}}{{{appDescription}}} +{{#appDescription}} +{{{appDescription}}} {{/appDescription}} {{#version}}OpenAPI spec version: {{version}}{{/version}} {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} Generated by: https://github.com/swagger-api/swagger-codegen.git -{{#licenseInfo}} -License: {{{licenseInfo}}} -{{#licenseUrl}}{{licenseUrl}}{{/licenseUrl}} +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 -{{/licenseInfo}} -{{#termsOfService}} -Terms of Service: {{{termsOfService}}} -{{/termsOfService}} +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. diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 87877d1763e..0c15a9929f3 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -86,7 +86,7 @@ # 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 + # @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) diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 160fa85a57d..e22b6d6f8a1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -1,3 +1,7 @@ +=begin +{{> api_info}} +=end + require 'uri' module {{moduleName}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache index 4c23a067175..6ea22543491 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache @@ -1,3 +1,7 @@ +=begin +{{> api_info}} +=end + require 'spec_helper' describe {{moduleName}}::Configuration do diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 65884d0f562..86d9a6e55d8 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -1,4 +1,9 @@ # -*- encoding: utf-8 -*- +# +=begin +{{> api_info}} +=end + $:.push File.expand_path("../lib", __FILE__) require "{{gemName}}/version" diff --git a/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache index e153ce23ecf..3def1140afc 100755 --- a/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache @@ -1,4 +1,19 @@ #!/bin/sh +# +# 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. +# # 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" @@ -28,7 +43,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/swagger-codegen/src/main/resources/ruby/gitignore.mustache b/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache index a8b1cda23f8..522134fcdd3 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache @@ -1,3 +1,17 @@ +# 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. + *.gem *.rbc /.config diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 14f26898d2b..33a5d134029 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -4,239 +4,6 @@ require 'date' -module {{moduleName}}{{#models}}{{#model}}{{#description}} - # {{{description}}}{{/description}} - class {{classname}}{{#vars}}{{#description}} - # {{{description}}}{{/description}} - attr_accessor :{{{name}}} -{{/vars}} - - # Attribute mapping from ruby-style variable name to JSON key. - def self.attribute_map - { - {{#vars}} - :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - # Attribute type mapping. - def self.swagger_types - { - {{#vars}} - :'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - 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} - - {{#vars}} - if attributes.has_key?(:'{{{baseName}}}') - {{#isContainer}} - if (value = attributes[:'{{{baseName}}}']).is_a?(Array) - self.{{{name}}} = value - end - {{/isContainer}} - {{^isContainer}} - self.{{{name}}} = attributes[:'{{{baseName}}}'] - {{/isContainer}} - {{#defaultValue}} - else - self.{{{name}}} = {{{defaultValue}}} - {{/defaultValue}} - end - - {{/vars}} - end - - # Show invalid properties with the reasons. Usually used together with valid? - # @return Array for valid properies with the reasons - def list_invalid_properties - invalid_properties = Array.new - {{#isEnum}} - allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] - if @{{{name}}} && !allowed_values.include?({{{name}}}) - invalid_properties.push("invalid value for '{{{name}}}', must be one of #{allowed_values}.") - end - - {{/isEnum}} - {{#hasValidation}} - if @{{{name}}}.nil? - fail ArgumentError, "{{{name}}} cannot be nil" - end - - {{#minLength}} - if @{{{name}}}.to_s.length > {{{maxLength}}} - invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.") - end - - {{/minLength}} - {{#maxLength}} - if @{{{name}}}.to_s.length < {{{minLength}}} - invalid_properties.push("invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}.") - end - - {{/maxLength}} - {{#maximum}} - if @{{{name}}} > {{{maximum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.") - end - - {{/maximum}} - {{#minimum}} - if @{{{name}}} < {{{minimum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}.") - end - - {{/minimum}} - {{#pattern}} - if @{{{name}}} !~ Regexp.new({{{pattern}}}) - invalid_properties.push("invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}.") - end - - {{/pattern}} - {{/hasValidation}} - return 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? - {{#vars}} - {{#required}} - if @{{{name}}}.nil? - return false - end - - {{/required}} - {{#isEnum}} - allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] - if @{{{name}}} && !allowed_values.include?(@{{{name}}}) - return false - end - {{/isEnum}} - {{#hasValidation}} - {{#minLength}} - if @{{{name}}}.to_s.length > {{{maxLength}}} - return false - end - - {{/minLength}} - {{#maxLength}} - if @{{{name}}}.to_s.length < {{{minLength}}} - return false - end - - {{/maxLength}} - {{#maximum}} - if @{{{name}}} > {{{maximum}}} - return false - end - - {{/maximum}} - {{#minimum}} - if @{{{name}}} < {{{minimum}}} - return false - end - - {{/minimum}} - {{#pattern}} - if @{{{name}}} !~ Regexp.new({{{pattern}}}) - return false - end - - {{/pattern}} - {{/hasValidation}} - {{/vars}} - end - - {{#vars}} - {{#isEnum}} - # Custom attribute writer method checking allowed values (enum). - # @param [Object] {{{name}}} Object to be assigned - def {{{name}}}=({{{name}}}) - allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] - if {{{name}}} && !allowed_values.include?({{{name}}}) - fail ArgumentError, "invalid value for '{{{name}}}', must be one of #{allowed_values}." - end - @{{{name}}} = {{{name}}} - end - - {{/isEnum}} - {{^isEnum}} - {{#hasValidation}} - # Custom attribute writer method with validation - # @param [Object] {{{name}}} Value to be assigned - def {{{name}}}=({{{name}}}) - if {{{name}}}.nil? - fail ArgumentError, "{{{name}}} cannot be nil" - end - - {{#minLength}} - if {{{name}}}.to_s.length > {{{maxLength}}} - fail ArgumentError, "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}." - end - - {{/minLength}} - {{#maxLength}} - if {{{name}}}.to_s.length < {{{minLength}}} - fail ArgumentError, "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}." - end - - {{/maxLength}} - {{#maximum}} - if {{{name}}} > {{{maximum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}." - end - - {{/maximum}} - {{#minimum}} - if {{{name}}} < {{{minimum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}." - end - - {{/minimum}} - {{#pattern}} - if @{{{name}}} !~ Regexp.new({{{pattern}}}) - fail ArgumentError, "invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}." - end - - {{/pattern}} - @{{{name}}} = {{{name}}} - end - - {{/hasValidation}} - {{/isEnum}} - {{/vars}} - # Checks equality by comparing each attribute. - # @param [Object] Object to be compared - def ==(o) - return true if self.equal?(o) - self.class == o.class{{#vars}} && - {{name}} == o.{{name}}{{/vars}} - 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 - [{{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}].hash - end - -{{> base_object}} - end -{{/model}} -{{/models}} +module {{moduleName}} +{{#models}}{{#model}}{{#isEnum}}{{>partial_model_enum_class}}{{/isEnum}}{{^isEnum}}{{>partial_model_generic}}{{/isEnum}}{{/model}}{{/models}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache index 305a10d6467..9425585780f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache @@ -27,7 +27,15 @@ require 'date' {{#vars}} describe 'test attribute "{{{name}}}"' do it 'should work' do + {{#isEnum}} + validator = Petstore::EnumTest::EnumAttributeValidator.new('{{{datatype}}}', [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]) + validator.allowable_values.each do |value| + expect { @instance.{{name}} = value }.not_to raise_error + end + {{/isEnum}} + {{^isEnum}} # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + {{/isEnum}} end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_enum_class.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_enum_class.mustache new file mode 100644 index 00000000000..e0e1ca9403d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_enum_class.mustache @@ -0,0 +1,4 @@ + class {{classname}} + {{#allowableValues}}{{#enumVars}} + {{{name}}} = {{{value}}}.freeze{{/enumVars}}{{/allowableValues}} + end diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache new file mode 100644 index 00000000000..0335500863f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -0,0 +1,230 @@ +{{#description}} # {{{description}}}{{/description}} + class {{classname}}{{#vars}}{{#description}} + # {{{description}}}{{/description}} + attr_accessor :{{{name}}} + {{/vars}} + +{{#hasEnums}} + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end +{{/hasEnums}} + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + {{#vars}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + # Attribute type mapping. + def self.swagger_types + { + {{#vars}} + :'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + 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} + + {{#vars}} + if attributes.has_key?(:'{{{baseName}}}') + {{#isContainer}} + if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + self.{{{name}}} = value + end + {{/isContainer}} + {{^isContainer}} + self.{{{name}}} = attributes[:'{{{baseName}}}'] + {{/isContainer}} + {{#defaultValue}} + else + self.{{{name}}} = {{{defaultValue}}} + {{/defaultValue}} + end + + {{/vars}} + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + {{#hasValidation}} + if @{{{name}}}.nil? + fail ArgumentError, "{{{name}}} cannot be nil" + end + + {{#minLength}} + if @{{{name}}}.to_s.length > {{{maxLength}}} + invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.") + end + + {{/minLength}} + {{#maxLength}} + if @{{{name}}}.to_s.length < {{{minLength}}} + invalid_properties.push("invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}.") + end + + {{/maxLength}} + {{#maximum}} + if @{{{name}}} > {{{maximum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.") + end + + {{/maximum}} + {{#minimum}} + if @{{{name}}} < {{{minimum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}.") + end + + {{/minimum}} + {{#pattern}} + if @{{{name}}} !~ Regexp.new({{{pattern}}}) + invalid_properties.push("invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}.") + end + + {{/pattern}} + {{/hasValidation}} + return 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? + {{#vars}} + {{#required}} + return false if @{{{name}}}.nil? + {{/required}} + {{#isEnum}} + {{{name}}}_validator = EnumAttributeValidator.new('{{{datatype}}}', [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]) + return false unless {{{name}}}_validator.valid?(@{{{name}}}) + {{/isEnum}} + {{#hasValidation}} + {{#minLength}} + return false if @{{{name}}}.to_s.length > {{{maxLength}}} + {{/minLength}} + {{#maxLength}} + return false if @{{{name}}}.to_s.length < {{{minLength}}} + {{/maxLength}} + {{#maximum}} + return false if @{{{name}}} > {{{maximum}}} + {{/maximum}} + {{#minimum}} + return false if @{{{name}}} < {{{minimum}}} + {{/minimum}} + {{#pattern}} + return false if @{{{name}}} !~ Regexp.new({{{pattern}}}) + {{/pattern}} + {{/hasValidation}} + {{/vars}} + return true + end + + {{#vars}} + {{#isEnum}} + # Custom attribute writer method checking allowed values (enum). + # @param [Object] {{{name}}} Object to be assigned + def {{{name}}}=({{{name}}}) + validator = EnumAttributeValidator.new('{{{datatype}}}', [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]) + unless validator.valid?({{{name}}}) + fail ArgumentError, "invalid value for '{{{name}}}', must be one of #{validator.allowable_values}." + end + @{{{name}}} = {{{name}}} + end + + {{/isEnum}} + {{^isEnum}} + {{#hasValidation}} + # Custom attribute writer method with validation + # @param [Object] {{{name}}} Value to be assigned + def {{{name}}}=({{{name}}}) + if {{{name}}}.nil? + fail ArgumentError, "{{{name}}} cannot be nil" + end + + {{#minLength}} + if {{{name}}}.to_s.length > {{{maxLength}}} + fail ArgumentError, "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}." + end + + {{/minLength}} + {{#maxLength}} + if {{{name}}}.to_s.length < {{{minLength}}} + fail ArgumentError, "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}." + end + + {{/maxLength}} + {{#maximum}} + if {{{name}}} > {{{maximum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}." + end + + {{/maximum}} + {{#minimum}} + if {{{name}}} < {{{minimum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}." + end + + {{/minimum}} + {{#pattern}} + if @{{{name}}} !~ Regexp.new({{{pattern}}}) + fail ArgumentError, "invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}." + end + + {{/pattern}} + @{{{name}}} = {{{name}}} + end + + {{/hasValidation}} + {{/isEnum}} + {{/vars}} + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class{{#vars}} && + {{name}} == o.{{name}}{{/vars}} + 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 + [{{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}].hash + end + +{{> base_object}} + end diff --git a/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache b/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache index bc4187c3378..8f4bb754165 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache @@ -1,3 +1,7 @@ +=begin +{{> api_info}} +=end + # load the gem require '{{{gemName}}}' diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 6345cd876c8..2600e71cffd 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -36,7 +36,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{/pathParams}} - val contentTypes = List({{#consumes}}"{{mediaType}}", {{/consumes}}"application/json") + val contentTypes = List({{#consumes}}"{{{mediaType}}}", {{/consumes}}"application/json") val contentType = contentTypes(0) // query params diff --git a/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache new file mode 100644 index 00000000000..88faa3610b2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" +} diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar differ diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache b/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache b/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache new file mode 100644 index 00000000000..b8fd6c4c41f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/slim/index.mustache b/modules/swagger-codegen/src/main/resources/slim/index.mustache index 4fdd77681c3..383094821dd 100644 --- a/modules/swagger-codegen/src/main/resources/slim/index.mustache +++ b/modules/swagger-codegen/src/main/resources/slim/index.mustache @@ -13,7 +13,7 @@ $app = new Slim\App(); * {{httpMethod}} {{nickname}} * Summary: {{summary}} * Notes: {{notes}} -{{#hasProduces}} * Output-Formats: [{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} +{{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ $app->{{httpMethod}}('{{path}}', function($request, $response, $args) { {{#hasHeaderParams}}$headers = $request->getHeaders();{{/hasHeaderParams}} diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/package.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/package.mustache index d728e9f0063..637b12bccc0 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/package.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/package.mustache @@ -8,5 +8,5 @@ "dependencies": { "express": "3.x" }, - "license": "apache 2.0" + "license": "Apache-2.0" } diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index 418f1c8512b..23e727b6b54 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -18,4 +18,23 @@ class APIHelper { } return destination } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + } diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 378c83525f1..17b9c2cd276 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -34,26 +34,26 @@ public class Response { private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary } - + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if T.self is Int32.Type && source is NSNumber { @@ -65,7 +65,7 @@ class Decoders { if source is T { return source as! T } - + let key = "\(T.self)" if let decoder = decoders[key] { return decoder(source) as! T @@ -100,14 +100,15 @@ class Decoders { Decoders.decode(clazz: clazz, source: someSource) } } - + static private func initialize() { dispatch_once(&once) { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'" + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() formatter.dateFormat = format @@ -121,7 +122,7 @@ class Decoders { return date } } - + } if let sourceInt = source as? Int { // treat as a java date diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 85b227ece87..3af6910a094 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -15,6 +15,6 @@ Pod::Spec.new do |s| s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} - s.dependency 'PromiseKit', '~> 3.0.0'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 3.1.4' + s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}} + s.dependency 'Alamofire', '~> 3.1.5' end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 9801182e082..298aa69e45e 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -16,6 +16,18 @@ extension {{projectName}}API { /** {{description}} */{{/description}} public class {{classname}}: APIBase { {{#operation}} + {{#allParams}} + {{#isEnum}} + /** + + enum for parameter {{paramName}} + */ + public enum {{{datatypeWithEnum}}}_{{operationId}}: String { {{#allowableValues}}{{#values}} + case {{enum}} = "{{raw}}"{{/values}}{{/allowableValues}} + } + + {{/isEnum}} + {{/allParams}} /** {{#summary}} {{{summary}}} @@ -23,7 +35,7 @@ public class {{classname}}: APIBase { - 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 */ - public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) { + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in completion({{#returnType}}data: response?.body, {{/returnType}}error: error); } @@ -37,7 +49,7 @@ public class {{classname}}: APIBase { - 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: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> */ - public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/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}}>.pendingPromise() {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in if let error = error { @@ -69,22 +81,25 @@ public class {{classname}}: APIBase { - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ - public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} - path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} + path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}}{{#isEnum}}.rawValue{{/isEnum}})", options: .LiteralSearch, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} - "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^required}}?{{/required}}.rawValue{{/isEnum}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} + let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index 96c4d2ff683..a42ff74a644 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -33,7 +33,7 @@ public class {{classname}}: JSONEncodable { public init() {} {{/unwrapRequired}} {{#unwrapRequired}} - public init({{#requiredVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}!{{/isEnum}}{{^isEnum}}{{datatype}}!{{/isEnum}}{{/requiredVars}}) { + public init({{#requiredVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{datatype}}{{/isEnum}}{{/requiredVars}}) { {{#requiredVars}} self.{{name}} = {{name}} {{/requiredVars}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache index 427479cf675..5a735cc58e1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -15,10 +15,10 @@ namespace {{package}} { protected basePath = '{{basePath}}'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index fd37bdd1194..817afd33f34 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -18,7 +19,7 @@ export class {{classname}} { protected basePath = '{{basePath}}'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } @@ -34,7 +35,7 @@ export class {{classname}} { const path = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; - let queryParameters: any = ""; // This should probably be an object in the future + let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; {{#hasFormParams}} let formParams = new URLSearchParams(); @@ -50,7 +51,7 @@ export class {{classname}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = {{paramName}}; + queryParameters.set('{{baseName}}', {{paramName}}); } {{/queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache index 05b5c6ec2ea..9a39b864538 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache @@ -1,9 +1,7 @@ {{#apiInfo}} {{#apis}} {{#operations}} -export * from '../api/{{classname}}'; +export * from './{{ classname }}'; {{/operations}} {{/apis}} -{{/apiInfo}} - - +{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache index 4170b2d1594..e8ce6c3642b 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache @@ -9,6 +9,7 @@ import * as models from './models'; */ {{/description}} export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{ + {{#additionalPropertiesType}}[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};{{/additionalPropertiesType}} {{#vars}} {{#description}} @@ -19,7 +20,6 @@ export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent} {{name}}?: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } - {{#hasEnums}} export namespace {{classname}} { {{#vars}} @@ -33,4 +33,4 @@ export namespace {{classname}} { } {{/hasEnums}} {{/model}} -{{/models}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/models.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/models.mustache index 677b6b87328..ace053bd55b 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/models.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/models.mustache @@ -3,6 +3,3 @@ export * from './{{{ classname }}}'; {{/model}} {{/models}} - - - diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 0b2e50acb44..70cb98cce7e 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -6,7 +6,7 @@ "keywords": [ "swagger-client" ], - "license": "MIT", + "license": "Apache-2.0", "files": [ "lib" ], @@ -16,17 +16,23 @@ "build": "typings install && tsc" }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }{{#npmRepository}}, "publishConfig":{ "registry":"{{npmRepository}}" diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache index 81163d686aa..2d1c16309bd 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -1,7 +1,7 @@ import request = require('request'); import http = require('http'); {{^supportsES6}} -import promise = require('bluebird'); +import Promise = require('bluebird'); {{/supportsES6}} let defaultBasePath = '{{basePath}}'; @@ -111,6 +111,7 @@ export enum {{classname}}ApiKeys { export class {{classname}} { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), @@ -151,12 +152,15 @@ export class {{classname}} { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: {{classname}}ApiKeys, value: string) { this.authentications[{{classname}}ApiKeys[key]].apiKey = value; } {{#authMethods}} {{#isBasic}} - set username(username: string) { this.authentications.{{name}}.username = username; } @@ -220,14 +224,12 @@ export class {{classname}} { {{/isFile}} {{/formParams}} - {{^supportsES6}} - let localVarDeferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>(); - {{/supportsES6}} let requestOptions: request.Options = { method: '{{httpMethod}}', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, {{#bodyParam}} body: {{paramName}}, @@ -247,22 +249,7 @@ export class {{classname}} { requestOptions.form = formParams; } } - {{^supportsES6}} - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - {{/supportsES6}} - {{#supportsES6}} - return new Promise<{ response: http.IncomingMessage; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>((resolve, reject) => { + return new Promise<{ response: http.{{#supportsES6}}IncomingMessage{{/supportsES6}}{{^supportsES6}}ClientResponse{{/supportsES6}}; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>((resolve, reject) => { request(requestOptions, (error, response, body) => { if (error) { reject(error); @@ -275,7 +262,6 @@ export class {{classname}} { } }); }); - {{/supportsES6}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/package.mustache index 96714500208..d7b5a8142a4 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/package.mustache @@ -2,12 +2,16 @@ "name": "{{npmName}}", "version": "{{npmVersion}}", "description": "NodeJS client for {{npmName}}", + "repository": "{{gitUserId}}/{{gitRepoId}}", "main": "api.js", "scripts": { - "build": "typings install && tsc" + "postinstall": "typings install", + "clean": "rm -Rf node_modules/ typings/ *.js", + "build": "tsc", + "test": "npm run build && node client.js" }, "author": "Swagger Codegen Contributors", - "license": "MIT", + "license": "Apache-2.0", "dependencies": { "bluebird": "^3.3.5", "request": "^2.72.0" diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache index 1a3bd00183a..e47082e11e9 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache @@ -10,9 +10,10 @@ "noLib": false, "declaration": true }, - "files": [ - "api.ts", - "typings/main.d.ts" + "exclude": [ + "node_modules", + "typings/browser", + "typings/browser.d.ts" ] } diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/typings.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/typings.mustache index 76c4cc8e6af..22fcebdc231 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/typings.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/typings.mustache @@ -1,10 +1,10 @@ { "ambientDependencies": { - "bluebird": "registry:dt/bluebird#2.0.0+20160319051630", "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914" }, "dependencies": { + "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "request": "registry:npm/request#2.69.0+20160304121250" } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java new file mode 100644 index 00000000000..8aaa127c6d8 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java @@ -0,0 +1,46 @@ +package io.swagger.codegen; + +import org.testng.annotations.Test; +import org.testng.reporters.Files; + +import java.io.IOException; +import java.util.Map; + +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + +import static io.swagger.codegen.testutils.AssertFile.assertPathEqualsRecursively; + +public abstract class AbstractIntegrationTest { + + protected abstract IntegrationTestPathsConfig getIntegrationTestPathsConfig(); + + protected abstract CodegenConfig getCodegenConfig(); + + protected abstract Map configProperties(); + + // @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(); + IntegrationTestPathsConfig integrationTestPathsConfig = getIntegrationTestPathsConfig(); + + String specContent = Files.readFile(integrationTestPathsConfig.getSpecPath().toFile()); + Swagger swagger = new SwaggerParser().parse(specContent); + + CodegenConfig codegenConfig = getCodegenConfig(); + codegenConfig.setOutputDir(integrationTestPathsConfig.getOutputPath().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/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java index f82e40bb41c..dfa4337e081 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java @@ -77,6 +77,40 @@ public class InlineModelResolverTest { 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 resolveInlineArrayModel() throws Exception { Swagger swagger = new Swagger(); @@ -128,6 +162,35 @@ public class InlineModelResolverTest { ModelImpl impl = (ModelImpl) body; assertNotNull(impl.getProperties().get("address")); } + + @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 { @@ -245,6 +308,50 @@ public class InlineModelResolverTest { 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(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java index 528666c58e5..5baf4f9eb1c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.Go; +package io.swagger.codegen.go; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; @@ -29,7 +29,7 @@ public class GoClientOptionsTest extends AbstractOptionsTest { clientCodegen.setPackageVersion(GoClientOptionsProvider.PACKAGE_VERSION_VALUE); times = 1; clientCodegen.setPackageName(GoClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java index 83fa8d6437e..ce9646398f0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.Go; +package io.swagger.codegen.go; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java new file mode 100644 index 00000000000..ef30ca48331 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java @@ -0,0 +1,152 @@ +package io.swagger.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("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/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java new file mode 100644 index 00000000000..f093507d84c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java @@ -0,0 +1,70 @@ +package io.swagger.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); + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java new file mode 100644 index 00000000000..17a96932d72 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java @@ -0,0 +1,158 @@ +package io.swagger.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/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java new file mode 100644 index 00000000000..471422fcc03 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java @@ -0,0 +1,285 @@ +package io.swagger.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/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java index 4a4e6ff9180..6080860735f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java @@ -17,7 +17,7 @@ import java.nio.charset.StandardCharsets; public class AllowableValuesTest { - private static final String TEMPLATE_FILE = "JavaJaxRS/jersey1_18/allowableValues.mustache"; + private static final String TEMPLATE_FILE = "JavaJaxRS/libraries/jersey1/allowableValues.mustache"; private static final String PROVIDER_NAME = "operations"; private static String loadClassResource(Class cls, String name) throws IOException { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index ddc8f2af06f..51dcd5fc90d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -46,7 +46,8 @@ public class JaxRSServerOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JaxRSServerOptionsProvider.DEFAULT_LIBRARY_VALUE); + //clientCodegen.setLibrary(JaxRSServerOptionsProvider.JAXRS_LIBRARY_VALUE); + clientCodegen.setLibrary("jersey1"); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java index 71d9b3942f1..dcb89d263cc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.slim; +package io.swagger.codegen.lumen; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java index 795c6ee2d9c..f1d55e007da 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java @@ -38,8 +38,6 @@ public class ObjcClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGitRepoURL(ObjcClientOptionsProvider.GIT_REPO_URL_VALUE); times = 1; - clientCodegen.setLicense(ObjcClientOptionsProvider.LICENSE_VALUE); - times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index 84fb38d1dd3..f3948b00781 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -1,21 +1,9 @@ package io.swagger.codegen.objc; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.*; import io.swagger.codegen.languages.ObjcClientCodegen; -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.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.*; +import io.swagger.models.properties.*; import io.swagger.parser.SwaggerParser; import com.google.common.collect.Sets; @@ -279,6 +267,20 @@ public class ObjcModelTest { Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); } + @Test(description = "test binary data") + public void binaryDataModelTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + 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()); + + 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 = "create proper imports per #316") public void issue316Test() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 82bb13029e5..82ffa437f2a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -18,7 +18,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { 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 LIBRARY_VALUE = "volley"; + public static final String LIBRARY_VALUE = "httpclient"; @Override public String getLanguage() { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index f2735614f19..3006ed396c9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -2,12 +2,27 @@ package io.swagger.codegen.options; import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; import java.util.Map; -public class JaxRSServerOptionsProvider extends JavaOptionsProvider { +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 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 IMPL_FOLDER_VALUE = "src/main/java/impl"; + public static final String JAXRS_DEFAULT_LIBRARY_VALUE = "jersey1"; @Override public boolean isServer() { @@ -21,13 +36,27 @@ public class JaxRSServerOptionsProvider extends JavaOptionsProvider { @Override public Map createOptions() { - Map options = super.createOptions(); - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - builder.putAll(options) - .put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE) - //.put(JavaJaxRSJersey1ServerCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda - .put("title", "Test title"); + 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("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.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.USE_RX_JAVA, "false") + //.put(JavaClientCodegen.DATE_LIBRARY, "joda") + .put("hideGenerationTimestamp", "true"); return builder.build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java index 2f76199e4f3..4df5c5e1db6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java @@ -9,12 +9,12 @@ import java.util.Map; public class ObjcClientOptionsProvider implements OptionsProvider { public static final String CLASS_PREFIX_VALUE = "SWGObjc"; + public static final String CORE_DATA_VALUE = "n"; public static final String POD_NAME_VALUE = "SwaggerClientObjc"; public static final String POD_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String AUTHOR_NAME_VALUE = "SwaggerObjc"; public static final String AUTHOR_EMAIL_VALUE = "objc@swagger.io"; public static final String GIT_REPO_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; - public static final String LICENSE_VALUE = "MIT"; @Override public String getLanguage() { @@ -30,7 +30,7 @@ public class ObjcClientOptionsProvider implements OptionsProvider { .put(ObjcClientCodegen.AUTHOR_NAME, AUTHOR_NAME_VALUE) .put(ObjcClientCodegen.AUTHOR_EMAIL, AUTHOR_EMAIL_VALUE) .put(ObjcClientCodegen.GIT_REPO_URL, GIT_REPO_URL_VALUE) - .put(ObjcClientCodegen.LICENSE, LICENSE_VALUE) + .put(ObjcClientCodegen.CORE_DATA, CORE_DATA_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java index dcd7a06438f..8aa37f12fd0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java @@ -18,6 +18,8 @@ public class PhpClientOptionsProvider implements OptionsProvider { 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"; @Override @@ -37,7 +39,9 @@ public class PhpClientOptionsProvider implements OptionsProvider { .put(PhpClientCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) .put(PhpClientCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) .put(PhpClientCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE) + .put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE) .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) + .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java new file mode 100644 index 00000000000..c75053b84e2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java @@ -0,0 +1,23 @@ +package io.swagger.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/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java index af70fc1834a..c4b1281c1dc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java @@ -10,6 +10,8 @@ public class SpringBootServerOptionsProvider extends JavaOptionsProvider { public static final String CONFIG_PACKAGE_VALUE = "configPackage"; public static final String BASE_PACKAGE_VALUE = "basePackage"; public static final String LIBRARY_VALUE = "j8-async"; //FIXME hidding value from super class + public static final String INTERFACE_ONLY = "true"; + public static final String SINGLE_CONTENT_TYPES = "true"; @Override public String getLanguage() { @@ -22,6 +24,9 @@ public class SpringBootServerOptionsProvider extends JavaOptionsProvider { options.put(SpringBootServerCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); options.put(SpringBootServerCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); + options.put(SpringBootServerCodegen.INTERFACE_ONLY, INTERFACE_ONLY); + options.put(SpringBootServerCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); + return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java index fb5e21d1cce..76f31deaacd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java @@ -42,8 +42,12 @@ public class PhpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setComposerVendorName(PhpClientOptionsProvider.COMPOSER_VENDOR_NAME_VALUE); times = 1; + clientCodegen.setGitUserId(PhpClientOptionsProvider.GIT_USER_ID_VALUE); + times = 1; clientCodegen.setComposerProjectName(PhpClientOptionsProvider.COMPOSER_PROJECT_NAME_VALUE); times = 1; + clientCodegen.setGitRepoId(PhpClientOptionsProvider.GIT_REPO_ID_VALUE); + times = 1; clientCodegen.setArtifactVersion(PhpClientOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; }}; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java index a7ecdd9d974..c60ac3a582d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.springBoot; +package io.swagger.codegen.springboot; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.java.JavaClientOptionsTest; @@ -54,7 +54,11 @@ public class SpringBootServerOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setBasePackage(SpringBootServerOptionsProvider.BASE_PACKAGE_VALUE); times = 1; - + clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringBootServerOptionsProvider.INTERFACE_ONLY)); + times = 1; + clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringBootServerOptionsProvider.SINGLE_CONTENT_TYPES)); + times = 1; + }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java new file mode 100644 index 00000000000..f810e20eb0a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java @@ -0,0 +1,132 @@ +package io.swagger.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.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)); + } + + assertEquals(expectedDir.toFile().list(), + actualDir.toFile().list(), + 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: '" + expected.toAbsolutePath().toString() + "' \n"); + stringBuilder.append("\tfile: '" + actual.toAbsolutePath().toString() + "' \n"); + stringBuilder.append("\tdiffs:\n"); + + for (Delta delta: deltas) { + stringBuilder.append(delta.toString() + "\n"); + } + + fail(stringBuilder.toString()); + } + + } catch (IOException e) { + fail(e.getMessage(), e); + } + } +} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java new file mode 100644 index 00000000000..4335c69dd2d --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java @@ -0,0 +1,33 @@ +package io.swagger.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; + + public IntegrationTestPathsConfig(String location) { + this(location + "-spec.json", location + "-result", location + "-expected"); + } + + public IntegrationTestPathsConfig(String specLocation, String outputLocation, String expectedLocation) { + outputPath = INTEGRATION_TEST_PATH.resolve(outputLocation); + expectedPath = INTEGRATION_TEST_PATH.resolve(expectedLocation); + specPath = INTEGRATION_TEST_PATH.resolve(specLocation); + } + + public Path getOutputPath() { + return outputPath; + } + + public Path getSpecPath() { + return specPath; + } + + public Path getExpectedPath() { + return expectedPath; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java similarity index 96% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index 09f16799ad9..c2744cc8258 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptfetch; +package io.swagger.codegen.typescript.fetch; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java similarity index 96% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java index d2173fdb710..d1b0a4be233 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java @@ -1,6 +1,10 @@ -package io.swagger.codegen.typescriptfetch; +package io.swagger.codegen.typescript.fetch; import com.google.common.collect.Sets; + +import org.testng.Assert; +import org.testng.annotations.Test; + import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.DefaultCodegen; @@ -8,9 +12,11 @@ import io.swagger.codegen.languages.TypeScriptFetchClientCodegen; import io.swagger.models.ArrayModel; 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 io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; @SuppressWarnings("static-method") public class TypeScriptFetchModelTest { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java similarity index 95% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java index 70cfb3d250d..2a68ab37110 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptangular; +package io.swagger.codegen.typescript.typescriptangular; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java similarity index 99% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index 26e8f841be9..75ab210966d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptangular; +package io.swagger.codegen.typescript.typescriptangular; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java similarity index 95% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java index 74e575c4496..73ace65a207 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptangular2; +package io.swagger.codegen.typescript.typescriptangular2; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java similarity index 98% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ModelTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java index 3aa33df7da4..685495f03c2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptangular2; +package io.swagger.codegen.typescript.typescriptangular2; import com.google.common.collect.Sets; @@ -178,6 +178,7 @@ public class TypeScriptAngular2ModelTest { Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(cm.additionalPropertiesType, "models.Children"); Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")).size(), 1); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java new file mode 100644 index 00000000000..8b23105f28c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.typescript.typescriptangular2; + +import java.util.HashMap; +import java.util.Map; + +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; + +public class TypescriptAngular2AdditionalPropertiesIntegrationTest extends AbstractIntegrationTest { + + @Override + protected CodegenConfig getCodegenConfig() { + return new TypeScriptAngular2ClientCodegen(); + } + + @Override + protected Map configProperties() { + Map propeties = new HashMap<>(); + propeties.put("npmName", "additionalPropertiesTest"); + propeties.put("npmVersion", "1.0.2"); + propeties.put("snapshot", "false"); + + return propeties; + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("typescript/additional-properties"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java new file mode 100644 index 00000000000..b9a8868a6b8 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.typescript.typescriptangular2; + +import java.util.HashMap; +import java.util.Map; + +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; + +public class TypescriptAngular2ArrayAndObjectTest extends AbstractIntegrationTest { + + @Override + protected CodegenConfig getCodegenConfig() { + return new TypeScriptAngular2ClientCodegen(); + } + + @Override + protected Map configProperties() { + Map propeties = new HashMap<>(); + propeties.put("npmName", "arrayAndAnyTest"); + propeties.put("npmVersion", "1.0.2"); + propeties.put("snapshot", "false"); + + return propeties; + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("typescript/array-and-object"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java similarity index 95% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java index 72b55b0b39d..4872e1d419d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptnode; +package io.swagger.codegen.typescript.typescriptnode; import io.swagger.codegen.AbstractOptionsTest; import io.swagger.codegen.CodegenConfig; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java similarity index 99% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java index 81a67e87b87..37e4fb688e0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.typescriptnode; +package io.swagger.codegen.typescript.typescriptnode; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java new file mode 100644 index 00000000000..22bac4ea316 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java @@ -0,0 +1,33 @@ +package io.swagger.codegen.typescript.typescriptnode; + +import java.util.HashMap; +import java.util.Map; + +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptNodeClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; + +public class TypescriptNodeES5IntegrationTest extends AbstractIntegrationTest { + + @Override + protected CodegenConfig getCodegenConfig() { + return new TypeScriptNodeClientCodegen(); + } + + @Override + protected Map configProperties() { + Map propeties = new HashMap<>(); + propeties.put("npmName", "node-es6-test"); + propeties.put("npmVersion", "1.0.3"); + propeties.put("snapshot", "false"); + propeties.put("supportsES6", "false"); + + return propeties; + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("typescript/node-es5"); + } +} diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index b9fa750d38a..ee4c0bfbcc9 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -575,9 +575,12 @@ paths: 偽のエンドポイント 가짜 엔드 포인트 operationId: testEndpointParameters + consumes: + - application/xml; charset=utf-8 + - application/json; charset=utf-8 produces: - - application/xml - - application/json + - application/xml; charset=utf-8 + - application/json; charset=utf-8 parameters: - name: integer type: integer @@ -944,6 +947,60 @@ definitions: enum: - 1.1 - -1.2 + 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: '#/definitions/Animal' + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + 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: '#/definitions/ReadOnlyFirst' externalDocs: description: Find out more about Swagger url: 'http://swagger.io' diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.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 +# Thsi 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/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md new file mode 100644 index 00000000000..b5338574869 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md @@ -0,0 +1,33 @@ +## additionalPropertiesTest@1.0.2 + +### 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 additionalPropertiesTest@1.0.2 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +In your angular2 project: + +TODO: paste example. diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/UserApi.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/UserApi.ts new file mode 100644 index 00000000000..77b6c013a8b --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/UserApi.ts @@ -0,0 +1,64 @@ +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import * as models from '../model/models'; +import 'rxjs/Rx'; + +/* tslint:disable:no-unused-variable member-ordering */ + +'use strict'; + +@Injectable() +export class UserApi { + protected basePath = 'http://additional-properties.swagger.io/v2'; + public defaultHeaders : Headers = new Headers(); + + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Add a new User to the store + * + * @param body User object that needs to be added to the store + */ + public addUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/user'; + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + let requestOptions: RequestOptionsArgs = { + method: 'POST', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = JSON.stringify(body); + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + + /** + * Update an existing User + * + * @param body User object that needs to be added to the store + */ + public updateUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/user'; + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + let requestOptions: RequestOptionsArgs = { + method: 'PUT', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = JSON.stringify(body); + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts new file mode 100644 index 00000000000..d3bd8432806 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts @@ -0,0 +1 @@ +export * from './UserApi'; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts new file mode 100644 index 00000000000..cdfea183ad3 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/User.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/User.ts new file mode 100644 index 00000000000..66f270cea01 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/User.ts @@ -0,0 +1,13 @@ +'use strict'; +import * as models from './models'; + +export interface User { + [key: string]: string | any; + + id?: number; + + /** + * User Status + */ + userStatus?: number; +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/models.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/models.ts new file mode 100644 index 00000000000..f6b9f36c6e1 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/model/models.ts @@ -0,0 +1 @@ +export * from './User'; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json new file mode 100644 index 00000000000..bdd490f27b9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json @@ -0,0 +1,36 @@ +{ + "name": "additionalPropertiesTest", + "version": "1.0.2", + "description": "swagger client for additionalPropertiesTest", + "author": "Swagger Codegen Contributors", + "keywords": [ + "swagger-client" + ], + "license": "Apache-2.0", + "files": [ + "lib" + ], + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "scripts": { + "build": "typings install && tsc" + }, + "peerDependencies": { + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1" + }, + "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", + "typescript": "^1.8.10", + "typings": "^0.8.1", + "es6-shim": "^0.35.0", + "es7-reflect-metadata": "^1.6.0" + }} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json new file mode 100644 index 00000000000..07fbdf7e1b1 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./lib", + "noLib": false, + "declaration": true + }, + "exclude": [ + "node_modules", + "typings/main.d.ts", + "typings/main", + "lib" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts", + "typings/browser.d.ts" + ] +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json new file mode 100644 index 00000000000..0848dcffe31 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json @@ -0,0 +1,5 @@ +{ + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-spec.json new file mode 100644 index 00000000000..3a06b88986c --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-spec.json @@ -0,0 +1,110 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a test spec", + "version": "1.0.0", + "title": "Swagger Additional Properties", + "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": "additional-properties.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Add a new User to the store", + "description": "", + "operationId": "addUser", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "User object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Update an existing User", + "description": "", + "operationId": "updateUser", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "User object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "405": { + "description": "Validation exception" + }, + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + } + }, + "definitions": { + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "additionalProperties": { + "type": "string" + } + } + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.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 +# Thsi 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/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md new file mode 100644 index 00000000000..85e98e0f9d9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md @@ -0,0 +1,33 @@ +## arrayAndAnyTest@1.0.2 + +### 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 arrayAndAnyTest@1.0.2 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +In your angular2 project: + +TODO: paste example. diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/ProjectApi.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/ProjectApi.ts new file mode 100644 index 00000000000..dbcdbe5fb7a --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/ProjectApi.ts @@ -0,0 +1,218 @@ +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import * as models from '../model/models'; +import 'rxjs/Rx'; + +/* tslint:disable:no-unused-variable member-ordering */ + +'use strict'; + +@Injectable() +export class ProjectApi { + protected basePath = 'https://localhost/v1'; + public defaultHeaders : Headers = new Headers(); + + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Create a Project + * Creates an empty Project + * @param name + * @param address + * @param longitude + * @param latitude + * @param meta + */ + public createProject (name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any ) : Observable { + const path = this.basePath + '/projects'; + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + let formParams = new URLSearchParams(); + + headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + + formParams['name'] = name; + + formParams['address'] = address; + + formParams['longitude'] = longitude; + + formParams['latitude'] = latitude; + + formParams['meta'] = meta; + + let requestOptions: RequestOptionsArgs = { + method: 'POST', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = formParams.toString(); + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + + /** + * Delete a Project + * Returns a Project JSON object + * @param id Project id + */ + public deleteProjectById (id: number, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/projects/{id}' + .replace('{' + 'id' + '}', String(id)); + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + // verify required parameter 'id' is set + if (!id) { + throw new Error('Missing required parameter id when calling deleteProjectById'); + } + let requestOptions: RequestOptionsArgs = { + method: 'DELETE', + headers: headerParams, + search: queryParameters + }; + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + + /** + * Get a Project + * Returns a Project JSON object + * @param id Project id + */ + public getProjectById (id: number, extraHttpRequestParams?: any ) : Observable { + const path = this.basePath + '/projects/{id}' + .replace('{' + 'id' + '}', String(id)); + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + // verify required parameter 'id' is set + if (!id) { + throw new Error('Missing required parameter id when calling getProjectById'); + } + let requestOptions: RequestOptionsArgs = { + method: 'GET', + headers: headerParams, + search: queryParameters + }; + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + + /** + * Get project list + * Returns a Project JSON object + * @param page + * @param perPage + * @param kind + * @param q + * @param filter + * @param latitude Valid with kind as location + * @param longitude Valid with kind as location + * @param scope Valid with kind as location, and between 1~9 + */ + public getProjectList (page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any ) : Observable { + const path = this.basePath + '/projects'; + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + if (page !== undefined) { + queryParameters['page'] = page; + } + + if (perPage !== undefined) { + queryParameters['per_page'] = perPage; + } + + if (kind !== undefined) { + queryParameters['kind'] = kind; + } + + if (q !== undefined) { + queryParameters['q'] = q; + } + + if (filter !== undefined) { + queryParameters['filter'] = filter; + } + + if (latitude !== undefined) { + queryParameters['latitude'] = latitude; + } + + if (longitude !== undefined) { + queryParameters['longitude'] = longitude; + } + + if (scope !== undefined) { + queryParameters['scope'] = scope; + } + + let requestOptions: RequestOptionsArgs = { + method: 'GET', + headers: headerParams, + search: queryParameters + }; + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + + /** + * Update project + * + * @param id Project id + * @param name User ID + * @param address Address + * @param longitude + * @param latitude + * @param meta + * @param thumbnail Project thumbnail + */ + public updateProject (id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any ) : Observable { + const path = this.basePath + '/projects/{id}' + .replace('{' + 'id' + '}', String(id)); + + let queryParameters: any = ""; // This should probably be an object in the future + let headerParams = this.defaultHeaders; + let formParams = new URLSearchParams(); + + // verify required parameter 'id' is set + if (!id) { + throw new Error('Missing required parameter id when calling updateProject'); + } + headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + + formParams['name'] = name; + + formParams['address'] = address; + + formParams['longitude'] = longitude; + + formParams['latitude'] = latitude; + + formParams['meta'] = meta; + + formParams['thumbnail'] = thumbnail; + + let requestOptions: RequestOptionsArgs = { + method: 'PUT', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = formParams.toString(); + + return this.http.request(path, requestOptions) + .map((response: Response) => response.json()); + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts new file mode 100644 index 00000000000..d919ee6d629 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts @@ -0,0 +1 @@ +export * from './ProjectApi'; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntity.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntity.ts new file mode 100644 index 00000000000..dc3bd6bdce9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntity.ts @@ -0,0 +1,32 @@ +'use strict'; +import * as models from './models'; + +export interface ProjectEntity { + + + id?: number; + + kind?: ProjectEntity.KindEnum; + + thumbnailUrl?: string; + + name?: string; + + state?: string; + + meta?: any; + + location?: models.ProjectEntityLocation; + + createdAt?: Date; + + updatedAt?: Date; + + publishedAt?: Date; +} +export namespace ProjectEntity { + + export enum KindEnum { + project = 'project', + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntityLocation.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntityLocation.ts new file mode 100644 index 00000000000..81fd66511a6 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectEntityLocation.ts @@ -0,0 +1,10 @@ +'use strict'; +import * as models from './models'; + +export interface ProjectEntityLocation { + + + lat?: number; + + lon?: number; +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectList.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectList.ts new file mode 100644 index 00000000000..a8a98e93a75 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/ProjectList.ts @@ -0,0 +1,8 @@ +'use strict'; +import * as models from './models'; + +export interface ProjectList { + + + contents?: Array; +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/models.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/models.ts new file mode 100644 index 00000000000..b917c007157 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/model/models.ts @@ -0,0 +1,3 @@ +export * from './ProjectEntity'; +export * from './ProjectEntityLocation'; +export * from './ProjectList'; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json new file mode 100644 index 00000000000..adc902b3610 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json @@ -0,0 +1,36 @@ +{ + "name": "arrayAndAnyTest", + "version": "1.0.2", + "description": "swagger client for arrayAndAnyTest", + "author": "Swagger Codegen Contributors", + "keywords": [ + "swagger-client" + ], + "license": "Apache-2.0", + "files": [ + "lib" + ], + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "scripts": { + "build": "typings install && tsc" + }, + "peerDependencies": { + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1" + }, + "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", + "typescript": "^1.8.10", + "typings": "^0.8.1", + "es6-shim": "^0.35.0", + "es7-reflect-metadata": "^1.6.0" + }} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json new file mode 100644 index 00000000000..07fbdf7e1b1 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./lib", + "noLib": false, + "declaration": true + }, + "exclude": [ + "node_modules", + "typings/main.d.ts", + "typings/main", + "lib" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts", + "typings/browser.d.ts" + ] +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json new file mode 100644 index 00000000000..0848dcffe31 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json @@ -0,0 +1,5 @@ +{ + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-spec.json new file mode 100644 index 00000000000..366cbb9cb39 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-spec.json @@ -0,0 +1,570 @@ +{ + "swagger": "2.0", + "info": + { + "version": "1.7.0", + "title": "Cupix API", + "contact": + { + "name": "inska.lee@cupix.com" + } + }, + "basePath": "/v1", + "consumes": + [ + "application/json" + ], + "produces": + [ + "application/json" + ], + "schemes": + [ + "https" + ], + "paths": + { + "/projects": + { + "post": + { + "tags": + [ + "Project" + ], + "summary": "Create a Project", + "operationId": "create_project", + "description": "Creates an empty Project", + "consumes": + [ + "application/x-www-form-urlencoded" + ], + "produces": + [ + "application/json" + ], + "parameters": + [ + + { + "name": "name", + "type": "string", + "in": "formData" + }, + + { + "name": "address", + "type": "string", + "in": "formData" + }, + + { + "name": "longitude", + "type": "number", + "format": "float", + "in": "formData" + }, + + { + "name": "latitude", + "type": "number", + "format": "float", + "in": "formData" + }, + + { + "name": "meta", + "type": "string", + "in": "formData" + } + ], + "responses": + { + "200": + { + "description": "Project information", + "schema": + { + "$ref": "#/definitions/ProjectEntity" + } + }, + "400": + { + "description": "Bad Request", + "schema": + { + "$ref": "#/definitions/Error" + } + }, + "401": + { + "description": "Unauthorized request" + }, + "403": + { + "description": "Forbidden" + }, + "404": + { + "description": "Project not found" + } + } + }, + "get": + { + "tags": + [ + "Project" + ], + "summary": "Get project list", + "operationId": "get_project_list", + "description": "Returns a Project JSON object", + "produces": + [ + "application/json" + ], + "security": + [ + + { + "key": + [ + + ] + }, + + { + "token": + [ + + ] + } + ], + "parameters": + [ + + { + "name": "page", + "type": "integer", + "format": "int32", + "in": "query" + }, + + { + "name": "per_page", + "type": "integer", + "format": "int32", + "in": "query" + }, + + { + "name": "kind", + "type": "string", + "in": "query", + "enum": + [ + "my_models", + "published", + "location" + ] + }, + + { + "name": "q", + "type": "string", + "in": "query" + }, + + { + "name": "filter", + "type": "string", + "in": "query" + }, + + { + "name": "latitude", + "in": "query", + "type": "number", + "format": "float", + "description": "Valid with kind as location" + }, + + { + "name": "longitude", + "in": "query", + "type": "number", + "format": "float", + "description": "Valid with kind as location" + }, + + { + "name": "scope", + "in": "query", + "type": "integer", + "description": "Valid with kind as location, and between 1~9" + } + ], + "responses": + { + "200": + { + "description": "Project list", + "schema": + { + "$ref": "#/definitions/ProjectList" + } + }, + "400": + { + "description": "Bad Request", + "schema": + { + "$ref": "#/definitions/Error" + } + }, + "401": + { + "description": "Unauthorized request" + }, + "403": + { + "description": "Forbidden" + }, + "404": + { + "description": "Project not found" + } + } + } + }, + "/projects/{id}": + { + "get": + { + "tags": + [ + "Project" + ], + "summary": "Get a Project", + "operationId": "get_project_by_id", + "description": "Returns a Project JSON object", + "produces": + [ + "application/json" + ], + "parameters": + [ + + { + "name": "id", + "in": "path", + "description": "Project id", + "required": true, + "type": "integer", + "format": "int32" + } + ], + "responses": + { + "200": + { + "description": "Project information", + "schema": + { + "$ref": "#/definitions/ProjectEntity" + } + }, + "400": + { + "description": "Bad Request", + "schema": + { + "$ref": "#/definitions/Error" + } + }, + "401": + { + "description": "Unauthorized request" + }, + "403": + { + "description": "Forbidden" + }, + "404": + { + "description": "Project not found" + } + } + }, + "put": + { + "tags": + [ + "Project" + ], + "summary": "Update project", + "operationId": "update_project", + "consumes": + [ + "multipart/form-data" + ], + "produces": + [ + "application/json" + ], + "parameters": + [ + + { + "name": "id", + "in": "path", + "description": "Project id", + "required": true, + "type": "integer", + "format": "int32" + }, + + { + "name": "name", + "in": "formData", + "description": "User ID", + "type": "string" + }, + + { + "name": "address", + "in": "formData", + "description": "Address", + "type": "string" + }, + + { + "name": "longitude", + "type": "number", + "format": "float", + "in": "formData" + }, + + { + "name": "latitude", + "type": "number", + "format": "float", + "in": "formData" + }, + + { + "name": "meta", + "type": "string", + "in": "formData" + }, + + { + "name": "thumbnail", + "in": "formData", + "description": "Project thumbnail", + "type": "file" + } + ], + "responses": + { + "200": + { + "description": "Project information", + "schema": + { + "$ref": "#/definitions/ProjectEntity" + } + }, + "400": + { + "description": "Bad Request", + "schema": + { + "$ref": "#/definitions/Error" + } + }, + "401": + { + "description": "Unauthorized request" + }, + "403": + { + "description": "Forbidden" + }, + "404": + { + "description": "Project not found" + } + } + }, + "delete": + { + "tags": + [ + "Project" + ], + "summary": "Delete a Project", + "operationId": "delete_project_by_id", + "description": "Returns a Project JSON object", + "produces": + [ + "application/json" + ], + "parameters": + [ + + { + "name": "id", + "in": "path", + "description": "Project id", + "required": true, + "type": "integer", + "format": "int32" + } + ], + "security": + [ + + { + "key": + [ + + ] + }, + + { + "token": + [ + + ] + } + ], + "responses": + { + "200": + { + "description": "Empty" + }, + "204": + { + "description": "Deleted" + }, + "400": + { + "description": "Bad Request", + "schema": + { + "$ref": "#/definitions/Error" + } + }, + "401": + { + "description": "Unauthorized request" + }, + "403": + { + "description": "Forbidden" + }, + "404": + { + "description": "Project not found" + } + } + } + } + }, + "definitions": + { + "ProjectList": + { + "type": "object", + "required": + [ + "contents" + ], + "properties": + { + "contents": + { + "type": "array", + "items": + { + "$ref": "#/definitions/ProjectEntity" + } + } + } + }, + "ProjectEntity": + { + "type": "object", + "required": + [ + "id" + ], + "properties": + { + "id": + { + "type": "integer", + "format": "int32" + }, + "kind": + { + "type": "string", + "enum": + [ + "project" + ] + }, + "thumbnail_url": + { + "type": "string" + }, + "name": + { + "type": "string" + }, + "state": + { + "type": "string" + }, + "meta": + { + "type": "object" + }, + "location": + { + "type": "object", + "properties": + { + "lat": + { + "type": "number", + "format": "float" + }, + "lon": + { + "type": "number", + "format": "float" + } + } + }, + "created_at": + { + "type": "string", + "format": "date-time" + }, + "updated_at": + { + "type": "string", + "format": "date-time" + }, + "published_at": + { + "type": "string", + "format": "date-time" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.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 +# Thsi 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/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/api.ts b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/api.ts new file mode 100644 index 00000000000..6a1cfed4d79 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/api.ts @@ -0,0 +1,594 @@ +import request = require('request'); +import http = require('http'); +import Promise = require('bluebird'); + +let defaultBasePath = 'http://petstore.swagger.io/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +export class Category { + 'id': number; + 'name': string; +} + +export class Pet { + 'id': number; + 'category': Category; + 'name': string; +} + + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +export class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +export class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +export class OAuth implements Authentication { + public accessToken: string; + + applyToRequest(requestOptions: request.Options): void { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } +} + +export class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export enum PetApiApiKeys { +} + +export class PetApi { + protected basePath = defaultBasePath; + protected defaultHeaders : any = {}; + + protected authentications = { + 'default': new VoidAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + public setApiKey(key: PetApiApiKeys, value: string) { + this.authentications[PetApiApiKeys[key]].apiKey = value; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + headerParams['api_key'] = apiKey; + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * 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: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let useFormData = false; + + if (name !== undefined) { + formParams['name'] = name; + } + + if (status !== undefined) { + formParams['status'] = status; + } + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} +export enum StoreApiApiKeys { +} + +export class StoreApi { + protected basePath = defaultBasePath; + protected defaultHeaders : any = {}; + + protected authentications = { + 'default': new VoidAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + public setApiKey(key: StoreApiApiKeys, value: string) { + this.authentications[StoreApiApiKeys[key]].apiKey = value; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * 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) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + const localVarPath = this.basePath + '/store/inventory'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * 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: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + const localVarPath = this.basePath + '/store/order'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/git_push.sh b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/git_push.sh new file mode 100644 index 00000000000..6ca091b49d9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/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="" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + 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="" + 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 crediential 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/test/resources/integrationtests/typescript/node-es5-expected/package.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/package.json new file mode 100644 index 00000000000..fba3fa017f9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/package.json @@ -0,0 +1,19 @@ +{ + "name": "node-es6-test", + "version": "1.0.3", + "description": "NodeJS client for node-es6-test", + "main": "api.js", + "scripts": { + "build": "typings install && tsc" + }, + "author": "Swagger Codegen Contributors", + "license": "Apache-2.0", + "dependencies": { + "bluebird": "^3.3.5", + "request": "^2.72.0" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/tsconfig.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/tsconfig.json new file mode 100644 index 00000000000..2dd166566e9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "ES5", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "noLib": false, + "declaration": true + }, + "files": [ + "api.ts", + "typings/main.d.ts" + ] +} + diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/typings.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/typings.json new file mode 100644 index 00000000000..76c4cc8e6af --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/typings.json @@ -0,0 +1,10 @@ +{ + "ambientDependencies": { + "bluebird": "registry:dt/bluebird#2.0.0+20160319051630", + "core-js": "registry:dt/core-js#0.0.0+20160317120654", + "node": "registry:dt/node#4.0.0+20160423143914" + }, + "dependencies": { + "request": "registry:npm/request#2.69.0+20160304121250" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-spec.json new file mode 100644 index 00000000000..2bf01d61584 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-spec.json @@ -0,0 +1,418 @@ +{ + "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.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": "/v1", + "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/{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" + ] + } + ] + } + }, + "/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" + } + } + } + } + }, + "definitions": { + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Pet": { + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 2d2b45d7892..7304fdd04bc 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.6 + 2.2.0-SNAPSHOT ../.. swagger-generator diff --git a/pom.xml b/pom.xml index 1b5c3d7580f..40ebc9bb85f 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.6 + 2.2.0-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -267,7 +267,7 @@ - samples/client/petstore/android/default + samples/client/petstore/android/volley @@ -411,7 +411,7 @@ - samples/client/petstore/swift/SwaggerClientTests + samples/client/petstore/swift/default/SwaggerClientTests @@ -435,7 +435,103 @@ - samples/server/petstore/jaxrs + samples/server/petstore/jaxrs/jersey2 + + + + jaxrs-server-jersey1 + + + env + java + + + + samples/server/petstore/jaxrs/jersey1 + + + + typescript-fetch-client-tests-default + + + env + java + + + + samples/client/petstore/typescript-fetch/tests/default + + + + typescript-fetch-client-builds-default + + + env + java + + + + samples/client/petstore/typescript-fetch/builds/default + + + + typescript-fetch-client-builds-es6-target + + + env + java + + + + samples/client/petstore/typescript-fetch/builds/es6-target + + + + typescript-fetch-client-builds-with-npm-version + + + env + java + + + + samples/client/petstore/typescript-fetch/builds/with-npm-version + + + + typescript-angular-client + + + env + java + + + + samples/client/petstore/typescript-angular/npm + + + + typescript-node-npm-client + + + env + java + + + + samples/client/petstore/typescript-node/npm + + + + python-client + + + env + java + + + + samples/client/petstore/python @@ -471,7 +567,17 @@ - samples/client/petstore/android/default + + samples/client/petstore/python + samples/client/petstore/ruby + samples/client/petstore/typescript-fetch/tests/default + samples/client/petstore/typescript-fetch/builds/default + samples/client/petstore/typescript-fetch/builds/es6-target + samples/client/petstore/typescript-fetch/builds/with-npm-version + samples/client/petstore/typescript-angular + samples/client/petstore/typescript-node/npm + samples/client/petstore/android/volley samples/client/petstore/clojure samples/client/petstore/java/default samples/client/petstore/java/feign @@ -483,8 +589,8 @@ samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc - samples/client/petstore/ruby - samples/server/petstore/jaxrs + samples/server/petstore/jaxrs/jersey1 + samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy @@ -562,7 +668,7 @@ 1.0.19 2.11.1 2.3.4 - 1.5.8 + 1.5.9 2.4 1.2 4.8.1 diff --git a/samples/client/petstore/android/default/.gitignore b/samples/client/petstore/android/httpclient/.gitignore similarity index 100% rename from samples/client/petstore/android/default/.gitignore rename to samples/client/petstore/android/httpclient/.gitignore diff --git a/samples/client/petstore/android/default/README.md b/samples/client/petstore/android/httpclient/README.md similarity index 100% rename from samples/client/petstore/android/default/README.md rename to samples/client/petstore/android/httpclient/README.md index a1c37674b81..65931066a32 100644 --- a/samples/client/petstore/android/default/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/default/build.gradle b/samples/client/petstore/android/httpclient/build.gradle similarity index 100% rename from samples/client/petstore/android/default/build.gradle rename to samples/client/petstore/android/httpclient/build.gradle diff --git a/samples/client/petstore/android/default/docs/Category.md b/samples/client/petstore/android/httpclient/docs/Category.md similarity index 100% rename from samples/client/petstore/android/default/docs/Category.md rename to samples/client/petstore/android/httpclient/docs/Category.md diff --git a/samples/client/petstore/android/default/docs/Order.md b/samples/client/petstore/android/httpclient/docs/Order.md similarity index 100% rename from samples/client/petstore/android/default/docs/Order.md rename to samples/client/petstore/android/httpclient/docs/Order.md diff --git a/samples/client/petstore/android/default/docs/Pet.md b/samples/client/petstore/android/httpclient/docs/Pet.md similarity index 100% rename from samples/client/petstore/android/default/docs/Pet.md rename to samples/client/petstore/android/httpclient/docs/Pet.md diff --git a/samples/client/petstore/android/default/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md similarity index 99% rename from samples/client/petstore/android/default/docs/PetApi.md rename to samples/client/petstore/android/httpclient/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/default/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/default/docs/StoreApi.md b/samples/client/petstore/android/httpclient/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/StoreApi.md rename to samples/client/petstore/android/httpclient/docs/StoreApi.md diff --git a/samples/client/petstore/android/default/docs/Tag.md b/samples/client/petstore/android/httpclient/docs/Tag.md similarity index 100% rename from samples/client/petstore/android/default/docs/Tag.md rename to samples/client/petstore/android/httpclient/docs/Tag.md diff --git a/samples/client/petstore/android/default/docs/User.md b/samples/client/petstore/android/httpclient/docs/User.md similarity index 100% rename from samples/client/petstore/android/default/docs/User.md rename to samples/client/petstore/android/httpclient/docs/User.md diff --git a/samples/client/petstore/android/default/docs/UserApi.md b/samples/client/petstore/android/httpclient/docs/UserApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/UserApi.md rename to samples/client/petstore/android/httpclient/docs/UserApi.md diff --git a/samples/client/petstore/android/default/git_push.sh b/samples/client/petstore/android/httpclient/git_push.sh similarity index 100% rename from samples/client/petstore/android/default/git_push.sh rename to samples/client/petstore/android/httpclient/git_push.sh diff --git a/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..fa452523ac0 --- /dev/null +++ b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon May 16 21:00:11 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/android/httpclient/gradlew b/samples/client/petstore/android/httpclient/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/android/httpclient/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/android/httpclient/gradlew.bat b/samples/client/petstore/android/httpclient/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/android/httpclient/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/android/default/pom.xml b/samples/client/petstore/android/httpclient/pom.xml similarity index 100% rename from samples/client/petstore/android/default/pom.xml rename to samples/client/petstore/android/httpclient/pom.xml diff --git a/samples/client/petstore/android/default/settings.gradle b/samples/client/petstore/android/httpclient/settings.gradle similarity index 100% rename from samples/client/petstore/android/default/settings.gradle rename to samples/client/petstore/android/httpclient/settings.gradle diff --git a/samples/client/petstore/android/default/src/main/AndroidManifest.xml b/samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/android/default/src/main/AndroidManifest.xml rename to samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..008a64a2444 --- /dev/null +++ b/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.jar @@ -0,0 +1,53 @@ +" zip.vim version v27 +" Browsing zipfile /Users/huangzhenjun/Public/git/PartTime/swagger-codegen/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar +" Select a file with cursor and press ENTER + +META-INF/ +META-INF/MANIFEST.MF +org/ +org/gradle/ +org/gradle/wrapper/ +org/gradle/wrapper/Download$1.class +org/gradle/wrapper/Download$SystemPropertiesProxyAuthenticator.class +org/gradle/wrapper/IDownload.class +org/gradle/wrapper/GradleUserHomeLookup.class +org/gradle/wrapper/ExclusiveFileAccessManager.class +org/gradle/wrapper/WrapperConfiguration.class +org/gradle/wrapper/SystemPropertiesHandler.class +org/gradle/wrapper/Logger.class +org/gradle/wrapper/PathAssembler.class +org/gradle/wrapper/Install.class +org/gradle/wrapper/BootstrapMainStarter.class +org/gradle/wrapper/WrapperExecutor.class +org/gradle/wrapper/GradleWrapperMain.class +org/gradle/wrapper/Install$1.class +org/gradle/wrapper/PathAssembler$LocalDistribution.class +org/gradle/wrapper/Download.class +gradle-wrapper-classpath.properties +build-receipt.properties +org/gradle/cli/ +org/gradle/cli/AbstractCommandLineConverter.class +org/gradle/cli/CommandLineParser$1.class +org/gradle/cli/CommandLineParser$MissingOptionArgState.class +org/gradle/cli/CommandLineParser$OptionStringComparator.class +org/gradle/cli/CommandLineArgumentException.class +org/gradle/cli/CommandLineParser$KnownOptionParserState.class +org/gradle/cli/CommandLineParser$OptionComparator.class +org/gradle/cli/CommandLineParser$UnknownOptionParserState.class +org/gradle/cli/CommandLineOption.class +org/gradle/cli/CommandLineParser$OptionParserState.class +org/gradle/cli/ParsedCommandLine.class +org/gradle/cli/ProjectPropertiesCommandLineConverter.class +org/gradle/cli/CommandLineParser$CaseInsensitiveStringComparator.class +org/gradle/cli/CommandLineParser.class +org/gradle/cli/CommandLineParser$AfterOptions.class +org/gradle/cli/CommandLineParser$OptionString.class +org/gradle/cli/AbstractPropertiesCommandLineConverter.class +org/gradle/cli/ParsedCommandLineOption.class +org/gradle/cli/CommandLineParser$OptionAwareParserState.class +org/gradle/cli/CommandLineConverter.class +org/gradle/cli/CommandLineParser$BeforeFirstSubCommand.class +org/gradle/cli/SystemPropertiesCommandLineConverter.class +org/gradle/cli/CommandLineParser$ParserState.class +org/gradle/cli/CommandLineParser$AfterFirstSubCommand.class +gradle-cli-classpath.properties diff --git a/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..fa452523ac0 --- /dev/null +++ b/samples/client/petstore/android/httpclient/src/main/java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon May 16 21:00:11 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java diff --git a/samples/client/petstore/android/volley/.gitignore b/samples/client/petstore/android/volley/.gitignore new file mode 100644 index 00000000000..a7b72d554da --- /dev/null +++ b/samples/client/petstore/android/volley/.gitignore @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks \ No newline at end of file diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index 6f0a2c65f92..65931066a32 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -1,4 +1,4 @@ -# swagger-petstore-android-volley +# swagger-android-client ## Requirements @@ -27,7 +27,7 @@ Add this dependency to your project's POM: ```xml io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 compile @@ -38,7 +38,7 @@ Add this dependency to your project's POM: Add this dependency to your project's build file: ```groovy -compile "io.swagger:swagger-petstore-android-volley:1.0.0" +compile "io.swagger:swagger-android-client:1.0.0" ``` ### Others @@ -49,7 +49,7 @@ At first generate the JAR by executing: Then manually install the following JARs: -* target/swagger-petstore-android-volley-1.0.0.jar +* target/swagger-android-client-1.0.0.jar * target/lib/*.jar ## Getting Started @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/volley/git_push.sh b/samples/client/petstore/android/volley/git_push.sh new file mode 100644 index 00000000000..f711c4b3130 --- /dev/null +++ b/samples/client/petstore/android/volley/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 crediential 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' \ No newline at end of file diff --git a/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..1bbc424ca7e --- /dev/null +++ b/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon May 16 21:00:31 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/android/volley/gradlew b/samples/client/petstore/android/volley/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/android/volley/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/android/volley/gradlew.bat b/samples/client/petstore/android/volley/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/android/volley/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml index 98572662fb2..04369688c3b 100644 --- a/samples/client/petstore/android/volley/pom.xml +++ b/samples/client/petstore/android/volley/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 diff --git a/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..126985b8a44 --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.jar @@ -0,0 +1,53 @@ +" zip.vim version v27 +" Browsing zipfile /Users/huangzhenjun/Public/git/PartTime/swagger-codegen/samples/client/petstore/android/volley/gradle/wrapper/gradle-wrapper.jar +" Select a file with cursor and press ENTER + +META-INF/ +META-INF/MANIFEST.MF +org/ +org/gradle/ +org/gradle/wrapper/ +org/gradle/wrapper/Download$1.class +org/gradle/wrapper/Download$SystemPropertiesProxyAuthenticator.class +org/gradle/wrapper/IDownload.class +org/gradle/wrapper/GradleUserHomeLookup.class +org/gradle/wrapper/ExclusiveFileAccessManager.class +org/gradle/wrapper/WrapperConfiguration.class +org/gradle/wrapper/SystemPropertiesHandler.class +org/gradle/wrapper/Logger.class +org/gradle/wrapper/PathAssembler.class +org/gradle/wrapper/Install.class +org/gradle/wrapper/BootstrapMainStarter.class +org/gradle/wrapper/WrapperExecutor.class +org/gradle/wrapper/GradleWrapperMain.class +org/gradle/wrapper/Install$1.class +org/gradle/wrapper/PathAssembler$LocalDistribution.class +org/gradle/wrapper/Download.class +gradle-wrapper-classpath.properties +build-receipt.properties +org/gradle/cli/ +org/gradle/cli/AbstractCommandLineConverter.class +org/gradle/cli/CommandLineParser$1.class +org/gradle/cli/CommandLineParser$MissingOptionArgState.class +org/gradle/cli/CommandLineParser$OptionStringComparator.class +org/gradle/cli/CommandLineArgumentException.class +org/gradle/cli/CommandLineParser$KnownOptionParserState.class +org/gradle/cli/CommandLineParser$OptionComparator.class +org/gradle/cli/CommandLineParser$UnknownOptionParserState.class +org/gradle/cli/CommandLineOption.class +org/gradle/cli/CommandLineParser$OptionParserState.class +org/gradle/cli/ParsedCommandLine.class +org/gradle/cli/ProjectPropertiesCommandLineConverter.class +org/gradle/cli/CommandLineParser$CaseInsensitiveStringComparator.class +org/gradle/cli/CommandLineParser.class +org/gradle/cli/CommandLineParser$AfterOptions.class +org/gradle/cli/CommandLineParser$OptionString.class +org/gradle/cli/AbstractPropertiesCommandLineConverter.class +org/gradle/cli/ParsedCommandLineOption.class +org/gradle/cli/CommandLineParser$OptionAwareParserState.class +org/gradle/cli/CommandLineConverter.class +org/gradle/cli/CommandLineParser$BeforeFirstSubCommand.class +org/gradle/cli/SystemPropertiesCommandLineConverter.class +org/gradle/cli/CommandLineParser$ParserState.class +org/gradle/cli/CommandLineParser$AfterFirstSubCommand.class +gradle-cli-classpath.properties diff --git a/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..1bbc424ca7e --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon May 16 21:00:31 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore new file mode 100644 index 00000000000..61ed08d3455 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore @@ -0,0 +1,24 @@ +# 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 +# Thsi 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 +src/IO.Swagger.Test/IO.Swagger.Test.csproj diff --git a/samples/client/petstore/csharp/SwaggerClient/.travis.yml b/samples/client/petstore/csharp/SwaggerClient/.travis.yml new file mode 100644 index 00000000000..4096e0b50d4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/.travis.yml @@ -0,0 +1,21 @@ +# +# 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. +# +language: csharp +mono: + - latest +solution: IO.Swagger.sln +script: + - /bin/sh ./mono_nunit_test.sh diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 3c26ad6be49..143ffeb1629 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{BF42B49D-37A0-49C4-A405-24CD946ADAA7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.Build.0 = Release|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Debug|Any CPU.Build.0 = Debug|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Release|Any CPU.ActiveCfg = Release|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/LICENSE b/samples/client/petstore/csharp/SwaggerClient/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index c546b834c18..c5a53af127d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ # IO.Swagger - the C# library for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +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 C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-05-10T17:39:13.582+08:00 +- Build date: 2016-06-12T16:29:47.553+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -54,7 +54,7 @@ namespace Example { var apiInstance = new FakeApi(); - var number = 3.4; // double? | None + var number = 3.4; // decimal? | None var _double = 1.2; // double? | None var _string = _string_example; // string | None var _byte = B; // byte[] | None @@ -112,20 +112,24 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Model.Animal](docs/Animal.md) - [Model.AnimalFarm](docs/AnimalFarm.md) - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.ArrayTest](docs/ArrayTest.md) - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) - [Model.Dog](docs/Dog.md) - [Model.EnumClass](docs/EnumClass.md) - [Model.EnumTest](docs/EnumTest.md) - [Model.FormatTest](docs/FormatTest.md) + - [Model.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model.Model200Response](docs/Model200Response.md) - [Model.ModelReturn](docs/ModelReturn.md) - [Model.Name](docs/Name.md) - [Model.Order](docs/Order.md) - [Model.Pet](docs/Pet.md) + - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Model.SpecialModelName](docs/SpecialModelName.md) - [Model.Tag](docs/Tag.md) - [Model.User](docs/User.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/build.bat b/samples/client/petstore/csharp/SwaggerClient/build.bat index 80a13e48231..ae94b120d7b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.bat +++ b/samples/client/petstore/csharp/SwaggerClient/build.bat @@ -1,3 +1,17 @@ +:: 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. + @echo off SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 @@ -8,7 +22,7 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll %CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClient/build.sh b/samples/client/petstore/csharp/SwaggerClient/build.sh index 159673fd60c..25228f3cc36 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.sh +++ b/samples/client/petstore/csharp/SwaggerClient/build.sh @@ -1,15 +1,35 @@ #!/usr/bin/env bash +# +# 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. + frameworkVersion=net45 netfx=${frameworkVersion#net} +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" wget -nc https://nuget.org/nuget.exe; mozroots --import --sync mono nuget.exe install src/IO.Swagger/packages.config -o packages; -mkdir -p bin; -cp packages/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.8.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; +echo "[INFO] Run 'mcs' to build bin/IO.Swagger.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ @@ -18,3 +38,11 @@ System.Runtime.Serialization.dll \ -recurse:'src/IO.Swagger/*.cs' \ -doc:bin/IO.Swagger.xml \ -platform:anycpu + +if [ $? -ne 0 ] +then + echo "[ERROR] Compilation failed with exit code $?" + exit 1 +else + echo "[INFO] bin/IO.Swagger.dll was created successfully" +fi diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClient/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ac4f9d10798 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/AdditionalPropertiesClass.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.AdditionalPropertiesClass +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **Dictionary<string, string>** | | [optional] +**MapOfMapProperty** | **Dictionary<string, Dictionary<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/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md new file mode 100644 index 00000000000..37fb2788b77 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.ArrayTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **List<string>** | | [optional] +**ArrayArrayOfInteger** | **List<List<long?>>** | | [optional] +**ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [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/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index 65b04a12ccb..cc24d4dfa07 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **TestEndpointParameters** -> void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) +> void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -30,7 +30,7 @@ namespace Example { var apiInstance = new FakeApi(); - var number = 3.4; // double? | None + var number = 3.4; // decimal? | None var _double = 1.2; // double? | None var _string = _string_example; // string | None var _byte = B; // byte[] | None @@ -61,7 +61,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **double?**| None | + **number** | **decimal?**| None | **_double** | **double?**| None | **_string** | **string**| None | **_byte** | **byte[]**| None | @@ -84,8 +84,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 [[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/csharp/SwaggerClient/docs/FormatTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md index 7ddfad04d05..1d366bd7cab 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **Integer** | **int?** | | [optional] **Int32** | **int?** | | [optional] **Int64** | **long?** | | [optional] -**Number** | **double?** | | +**Number** | **decimal?** | | **_Float** | **float?** | | [optional] **_Double** | **double?** | | [optional] **_String** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClient/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e2c978f9ab1 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.MixedPropertiesAndAdditionalPropertiesClass +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **Guid?** | | [optional] +**DateTime** | **DateTime?** | | [optional] +**Map** | [**Dictionary<string, 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/client/petstore/csharp/SwaggerClient/docs/ReadOnlyFirst.md b/samples/client/petstore/csharp/SwaggerClient/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..b5f8d484869 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/ReadOnlyFirst.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.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/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh new file mode 100644 index 00000000000..e7032942787 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# 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. + +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/SwaggerClientTest.dll" +rm src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync +mono nuget.exe install src/IO.Swagger.Test/packages.config -o packages + +echo "[INFO] Install NUnit runners via NuGet" +mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild IO.Swagger.sln && \ + mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs index 478311b649e..7f537b16558 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs @@ -48,7 +48,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a FakeApi"); + Assert.IsInstanceOfType(typeof(FakeApi), instance, "instance is a FakeApi"); } @@ -58,20 +58,22 @@ namespace IO.Swagger.Test [Test] public void TestEndpointParametersTest() { + /* comment out the following as the endpiont is fake // TODO: add unit test for the method 'TestEndpointParameters' - double? number = null; // TODO: replace null with proper value - double? _double = null; // TODO: replace null with proper value - string _string = null; // TODO: replace null with proper value - byte[] _byte = null; // TODO: replace null with proper value - int? integer = null; // TODO: replace null with proper value - int? int32 = null; // TODO: replace null with proper value - long? int64 = null; // TODO: replace null with proper value - float? _float = null; // TODO: replace null with proper value + double? number = 12.3; // TODO: replace null with proper value + double? _double = 34.5; // TODO: replace null with proper value + string _string = "charp test"; // TODO: replace null with proper value + byte[] _byte = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };; // TODO: replace null with proper value + int? integer = 3; // TODO: replace null with proper value + int? int32 = 2; // TODO: replace null with proper value + long? int64 = 1; // TODO: replace null with proper value + float? _float = 7.8F; // TODO: replace null with proper value byte[] binary = null; // TODO: replace null with proper value - DateTime? date = null; // TODO: replace null with proper value + DateTime? date = null; // TODO: replace null with proper value DateTime? dateTime = null; // TODO: replace null with proper value string password = null; // TODO: replace null with proper value instance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + */ } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs index a24e297eea1..0d517af68b5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs @@ -25,13 +25,59 @@ namespace IO.Swagger.Test { private PetApi instance; + private long petId = 11088; + + /// + /// Create a Pet object + /// + private Pet createPet() + { + // create pet + Pet p = new Pet(Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test" }); + p.Id = petId; + //p.Name = "Csharp test"; + p.Status = Pet.StatusEnum.Available; + // create Category object + Category category = new Category(); + category.Id = 56; + category.Name = "sample category name2"; + List photoUrls = new List(new String[] {"sample photoUrls"}); + // create Tag object + Tag tag = new Tag(); + tag.Id = petId; + tag.Name = "csharp sample tag name1"; + List tags = new List(new Tag[] {tag}); + p.Tags = tags; + p.Category = category; + p.PhotoUrls = photoUrls; + + return p; + } + + /// + /// Convert string to byte array + /// + private byte[] GetBytes(string str) + { + byte[] bytes = new byte[str.Length * sizeof(char)]; + System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); + return bytes; + } + /// /// Setup before each unit test /// [SetUp] public void Init() { - instance = new PetApi(); + instance = new PetApi(); + + // create pet + Pet p = createPet(); + + // add pet before testing + PetApi petApi = new PetApi("http://petstore.swagger.io/v2/"); + petApi.AddPet (p); } /// @@ -40,7 +86,9 @@ namespace IO.Swagger.Test [TearDown] public void Cleanup() { - + // remove the pet after testing + PetApi petApi = new PetApi (); + petApi.DeletePet(petId, "test key"); } /// @@ -49,7 +97,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a PetApi"); + Assert.IsInstanceOfType(typeof(PetApi), instance, "instance is a PetApi"); } @@ -59,10 +107,10 @@ namespace IO.Swagger.Test [Test] public void AddPetTest() { - // TODO: add unit test for the method 'AddPet' - Pet body = null; // TODO: replace null with proper value - instance.AddPet(body); - + // create pet + Pet p = createPet(); + + instance.AddPet(p); } /// @@ -71,11 +119,7 @@ namespace IO.Swagger.Test [Test] public void DeletePetTest() { - // TODO: add unit test for the method 'DeletePet' - long? petId = null; // TODO: replace null with proper value - string apiKey = null; // TODO: replace null with proper value - instance.DeletePet(petId, apiKey); - + // no need to test as it'c covered by Cleanup() already } /// @@ -84,10 +128,15 @@ namespace IO.Swagger.Test [Test] public void FindPetsByStatusTest() { - // TODO: add unit test for the method 'FindPetsByStatus' - List status = null; // TODO: replace null with proper value - var response = instance.FindPetsByStatus(status); - Assert.IsInstanceOf> (response, "response is List"); + PetApi petApi = new PetApi (); + List tagsList = new List(new String[] {"available"}); + + List listPet = petApi.FindPetsByTags (tagsList); + foreach (Pet pet in listPet) // Loop through List with foreach. + { + Assert.IsInstanceOfType(typeof(Pet), pet, "Response is a Pet"); + Assert.AreEqual ("csharp sample tag name1", pet.Tags[0]); + } } /// @@ -96,10 +145,9 @@ namespace IO.Swagger.Test [Test] public void FindPetsByTagsTest() { - // TODO: add unit test for the method 'FindPetsByTags' - List tags = null; // TODO: replace null with proper value + List tags = new List(new String[] {"pet"}); var response = instance.FindPetsByTags(tags); - Assert.IsInstanceOf> (response, "response is List"); + Assert.IsInstanceOfType(typeof(List), response, "response is List"); } /// @@ -108,22 +156,96 @@ namespace IO.Swagger.Test [Test] public void GetPetByIdTest() { - // TODO: add unit test for the method 'GetPetById' - long? petId = null; // TODO: replace null with proper value - var response = instance.GetPetById(petId); - Assert.IsInstanceOf (response, "response is Pet"); + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000, userAgent: "TEST_USER_AGENT"); + + PetApi petApi = new PetApi (c1); + Pet response = petApi.GetPetById (petId); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); + + Assert.AreEqual ("Csharp test", response.Name); + Assert.AreEqual (Pet.StatusEnum.Available, response.Status); + + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); + + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); + + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); + Assert.AreEqual (56, response.Category.Id); + Assert.AreEqual ("sample category name2", response.Category.Name); } + + /// + /// Test GetPetByIdAsync + /// + [Test ()] + public void TestGetPetByIdAsync () + { + PetApi petApi = new PetApi (); + var task = petApi.GetPetByIdAsync (petId); + Pet response = task.Result; + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); + + Assert.AreEqual ("Csharp test", response.Name); + Assert.AreEqual (Pet.StatusEnum.Available, response.Status); + + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); + + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); + + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); + Assert.AreEqual (56, response.Category.Id); + Assert.AreEqual ("sample category name2", response.Category.Name); + + } + /// + /// Test GetPetByIdAsyncWithHttpInfo + /// + [Test ()] + public void TestGetPetByIdAsyncWithHttpInfo () + { + PetApi petApi = new PetApi (); + var task = petApi.GetPetByIdAsyncWithHttpInfo (petId); + + Assert.AreEqual (200, task.Result.StatusCode); + Assert.IsTrue (task.Result.Headers.ContainsKey("Content-Type")); + Assert.AreEqual (task.Result.Headers["Content-Type"], "application/json"); + + Pet response = task.Result.Data; + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); + + Assert.AreEqual ("Csharp test", response.Name); + Assert.AreEqual (Pet.StatusEnum.Available, response.Status); + + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); + + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); + + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); + Assert.AreEqual (56, response.Category.Id); + Assert.AreEqual ("sample category name2", response.Category.Name); + + } + /// /// Test UpdatePet /// [Test] public void UpdatePetTest() { - // TODO: add unit test for the method 'UpdatePet' - Pet body = null; // TODO: replace null with proper value - instance.UpdatePet(body); - + // create pet + Pet p = createPet(); + instance.UpdatePet(p); } /// @@ -132,12 +254,24 @@ namespace IO.Swagger.Test [Test] public void UpdatePetWithFormTest() { - // TODO: add unit test for the method 'UpdatePetWithForm' - long? petId = null; // TODO: replace null with proper value - string name = null; // TODO: replace null with proper value - string status = null; // TODO: replace null with proper value - instance.UpdatePetWithForm(petId, name, status); - + PetApi petApi = new PetApi (); + petApi.UpdatePetWithForm (petId, "new form name", "pending"); + + Pet response = petApi.GetPetById (petId); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); + + Assert.AreEqual ("new form name", response.Name); + Assert.AreEqual (Pet.StatusEnum.Pending, response.Status); + + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual (56, response.Category.Id); + + // test optional parameter + petApi.UpdatePetWithForm (petId, "new form name2"); + Pet response2 = petApi.GetPetById (petId); + Assert.AreEqual ("new form name2", response2.Name); } /// @@ -146,13 +280,45 @@ namespace IO.Swagger.Test [Test] public void UploadFileTest() { - // TODO: add unit test for the method 'UploadFile' - long? petId = null; // TODO: replace null with proper value - string additionalMetadata = null; // TODO: replace null with proper value - System.IO.Stream file = null; // TODO: replace null with proper value - var response = instance.UploadFile(petId, additionalMetadata, file); - Assert.IsInstanceOf (response, "response is ApiResponse"); + Assembly _assembly = Assembly.GetExecutingAssembly(); + Stream _imageStream = _assembly.GetManifestResourceStream("IO.Swagger.Test.swagger-logo.png"); + PetApi petApi = new PetApi (); + // test file upload with form parameters + petApi.UploadFile(petId, "new form name", _imageStream); + + // test file upload without any form parameters + // using optional parameter syntax introduced at .net 4.0 + petApi.UploadFile(petId: petId, file: _imageStream); + } + + /// + /// Test status code + /// + [Test ()] + public void TestStatusCodeAndHeader () + { + PetApi petApi = new PetApi (); + var response = petApi.GetPetByIdWithHttpInfo (petId); + Assert.AreEqual (response.StatusCode, 200); + Assert.IsTrue (response.Headers.ContainsKey("Content-Type")); + Assert.AreEqual (response.Headers["Content-Type"], "application/json"); + } + + /// + /// Test default header (should be deprecated + /// + [Test ()] + public void TestDefaultHeader () + { + PetApi petApi = new PetApi (); + // commented out the warning test below as it's confirmed the warning is working as expected + // there should be a warning for using AddDefaultHeader (deprecated) below + //petApi.AddDefaultHeader ("header_key", "header_value"); + // the following should be used instead as suggested in the doc + petApi.Configuration.AddDefaultHeader ("header_key2", "header_value2"); + + } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs index 5ccac40bbfb..2ca3b35f30d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; +using Newtonsoft.Json; using IO.Swagger.Client; using IO.Swagger.Api; @@ -49,7 +50,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a StoreApi"); + Assert.IsInstanceOfType(typeof(StoreApi), instance, "instance is a StoreApi"); } @@ -60,8 +61,8 @@ namespace IO.Swagger.Test public void DeleteOrderTest() { // TODO: add unit test for the method 'DeleteOrder' - string orderId = null; // TODO: replace null with proper value - instance.DeleteOrder(orderId); + //string orderId = null; // TODO: replace null with proper value + //instance.DeleteOrder(orderId); } @@ -72,8 +73,19 @@ namespace IO.Swagger.Test public void GetInventoryTest() { // TODO: add unit test for the method 'GetInventory' - var response = instance.GetInventory(); - Assert.IsInstanceOf> (response, "response is Dictionary"); + //var response = instance.GetInventory(); + //Assert.IsInstanceOf> (response, "response is Dictionary"); + + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + StoreApi storeApi = new StoreApi (c1); + Dictionary response = storeApi.GetInventory (); + + foreach(KeyValuePair entry in response) + { + Assert.IsInstanceOfType(typeof(int?), entry.Value); + } } /// @@ -83,9 +95,9 @@ namespace IO.Swagger.Test public void GetOrderByIdTest() { // TODO: add unit test for the method 'GetOrderById' - long? orderId = null; // TODO: replace null with proper value - var response = instance.GetOrderById(orderId); - Assert.IsInstanceOf (response, "response is Order"); + //long? orderId = null; // TODO: replace null with proper value + //var response = instance.GetOrderById(orderId); + //Assert.IsInstanceOf (response, "response is Order"); } /// @@ -95,11 +107,41 @@ namespace IO.Swagger.Test public void PlaceOrderTest() { // TODO: add unit test for the method 'PlaceOrder' - Order body = null; // TODO: replace null with proper value - var response = instance.PlaceOrder(body); - Assert.IsInstanceOf (response, "response is Order"); + //Order body = null; // TODO: replace null with proper value + //var response = instance.PlaceOrder(body); + //Assert.IsInstanceOf (response, "response is Order"); } + /// + /// Test Enum + /// + [Test ()] + public void TestEnum () + { + Assert.AreEqual (Order.StatusEnum.Approved.ToString(), "Approved"); + } + + /// + /// Test deserialization of JSON to Order and its readonly property + /// + [Test ()] + public void TesOrderDeserialization() + { + string json = @"{ +'id': 1982, +'petId': 1020, +'quantity': 1, +'status': 'placed', +'complete': true, +}"; + var o = JsonConvert.DeserializeObject(json); + Assert.AreEqual (1982, o.Id); + Assert.AreEqual (1020, o.PetId); + Assert.AreEqual (1, o.Quantity); + Assert.AreEqual (Order.StatusEnum.Placed, o.Status); + Assert.AreEqual (true, o.Complete); + + } } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs index ffb0593aa88..31edf492923 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs @@ -49,7 +49,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a UserApi"); + Assert.IsInstanceOfType(typeof(UserApi), instance, "instance is a UserApi"); } @@ -60,8 +60,8 @@ namespace IO.Swagger.Test public void CreateUserTest() { // TODO: add unit test for the method 'CreateUser' - User body = null; // TODO: replace null with proper value - instance.CreateUser(body); + //User body = null; // TODO: replace null with proper value + //instance.CreateUser(body); } @@ -72,8 +72,8 @@ namespace IO.Swagger.Test public void CreateUsersWithArrayInputTest() { // TODO: add unit test for the method 'CreateUsersWithArrayInput' - List body = null; // TODO: replace null with proper value - instance.CreateUsersWithArrayInput(body); + //List body = null; // TODO: replace null with proper value + //instance.CreateUsersWithArrayInput(body); } @@ -84,8 +84,8 @@ namespace IO.Swagger.Test public void CreateUsersWithListInputTest() { // TODO: add unit test for the method 'CreateUsersWithListInput' - List body = null; // TODO: replace null with proper value - instance.CreateUsersWithListInput(body); + //List body = null; // TODO: replace null with proper value + //instance.CreateUsersWithListInput(body); } @@ -96,8 +96,8 @@ namespace IO.Swagger.Test public void DeleteUserTest() { // TODO: add unit test for the method 'DeleteUser' - string username = null; // TODO: replace null with proper value - instance.DeleteUser(username); + //string username = null; // TODO: replace null with proper value + //instance.DeleteUser(username); } @@ -108,9 +108,9 @@ namespace IO.Swagger.Test public void GetUserByNameTest() { // TODO: add unit test for the method 'GetUserByName' - string username = null; // TODO: replace null with proper value - var response = instance.GetUserByName(username); - Assert.IsInstanceOf (response, "response is User"); + //string username = null; // TODO: replace null with proper value + //var response = instance.GetUserByName(username); + //Assert.IsInstanceOf (response, "response is User"); } /// @@ -120,10 +120,10 @@ namespace IO.Swagger.Test public void LoginUserTest() { // TODO: add unit test for the method 'LoginUser' - string username = null; // TODO: replace null with proper value - string password = null; // TODO: replace null with proper value - var response = instance.LoginUser(username, password); - Assert.IsInstanceOf (response, "response is string"); + //string username = null; // TODO: replace null with proper value + //string password = null; // TODO: replace null with proper value + //var response = instance.LoginUser(username, password); + //Assert.IsInstanceOf (response, "response is string"); } /// @@ -133,7 +133,7 @@ namespace IO.Swagger.Test public void LogoutUserTest() { // TODO: add unit test for the method 'LogoutUser' - instance.LogoutUser(); + //instance.LogoutUser(); } @@ -144,9 +144,9 @@ namespace IO.Swagger.Test public void UpdateUserTest() { // TODO: add unit test for the method 'UpdateUser' - string username = null; // TODO: replace null with proper value - User body = null; // TODO: replace null with proper value - instance.UpdateUser(username, body); + //string username = null; // TODO: replace null with proper value + //User body = null; // TODO: replace null with proper value + //instance.UpdateUser(username, body); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ApiClientTests.cs similarity index 67% rename from samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ApiClientTests.cs index 9d1921d8ea7..4f31bc0b302 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ApiClientTests.cs @@ -3,17 +3,22 @@ using System; using System.Collections.Generic; using IO.Swagger.Client; using IO.Swagger.Api; +using IO.Swagger.Model; -namespace SwaggerClientTest.TestApiClient +namespace IO.Swagger.Test { - public class TestApiClient + public class ApiClientTests { - [TearDown()] - public void TearDown() - { - // Reset to default, just in case - Configuration.Default.DateTimeFormat = "o"; - } + public ApiClientTests () + { + } + + [TearDown()] + public void TearDown() + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } /// /// Test SelectHeaderContentType @@ -35,7 +40,7 @@ namespace SwaggerClientTest.TestApiClient /// /// Test ParameterToString /// - [Test ()] + [Test ()] public void TestParameterToString () { ApiClient api = new ApiClient (); @@ -49,8 +54,8 @@ namespace SwaggerClientTest.TestApiClient Assert.AreEqual("1,37", api.ParameterToString (numList)); } - [Test ()] - public void TestParameterToStringForDateTime () + [Test ()] + public void TestParameterToStringForDateTime () { ApiClient api = new ApiClient (); @@ -68,34 +73,34 @@ namespace SwaggerClientTest.TestApiClient public void TestParameterToStringWithTimeZoneForDateTime () { ApiClient api = new ApiClient (); - // test datetime with a time zone - DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); - Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); - } + // test datetime with a time zone + DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); + } - [Test ()] - public void TestParameterToStringForDateTimeWithUFormat () - { - // Setup the DateTimeFormat across all of the calls - Configuration.Default.DateTimeFormat = "u"; - ApiClient api = new ApiClient(); - - // test datetime - DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); - Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc)); - } + [Test ()] + public void TestParameterToStringForDateTimeWithUFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "u"; + ApiClient api = new ApiClient(); - [Test ()] - public void TestParameterToStringForDateTimeWithCustomFormat () - { - // Setup the DateTimeFormat across all of the calls - Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss"; - ApiClient api = new ApiClient(); + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc)); + } - // test datetime - DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); - Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc)); - } + [Test ()] + public void TestParameterToStringForDateTimeWithCustomFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss"; + ApiClient api = new ApiClient(); + + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc)); + } [Test ()] public void TestSanitizeFilename () @@ -104,7 +109,7 @@ namespace SwaggerClientTest.TestApiClient Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("../sun.gif")); Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("/var/tmp/sun.gif")); Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("./sun.gif")); - + Assert.AreEqual("sun", ApiClient.SanitizeFilename("sun")); Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("..\\sun.gif")); Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("\\var\\tmp\\sun.gif")); @@ -140,6 +145,5 @@ namespace SwaggerClientTest.TestApiClient Assert.AreNotSame(p4.Configuration.ApiClient, Configuration.Default.ApiClient); } - } -} - + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ConfigurationTests.cs similarity index 71% rename from samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ConfigurationTests.cs index 140fd269834..936751317ab 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Client/ConfigurationTests.cs @@ -5,16 +5,20 @@ using IO.Swagger.Client; using IO.Swagger.Api; using IO.Swagger.Model; -namespace SwaggerClientTest.TestConfiguration +namespace IO.Swagger.Test { - public class TestConfiguration + public class ConfigurationTests { - [TearDown ()] - public void TearDown () - { - // Reset to default, just in case - Configuration.Default.DateTimeFormat = "o"; - } + public ConfigurationTests () + { + } + + [TearDown ()] + public void TearDown () + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } [Test ()] public void TestAuthentication () @@ -39,21 +43,21 @@ namespace SwaggerClientTest.TestConfiguration Assert.AreNotSame (p.Configuration, Configuration.Default); } - [Test ()] - public void TestDateTimeFormat_Default () - { - // Should default to the Round-trip Format Specifier - "o" - // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 - Assert.AreEqual("o", Configuration.Default.DateTimeFormat); - } + [Test ()] + public void TestDateTimeFormat_Default () + { + // Should default to the Round-trip Format Specifier - "o" + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + Assert.AreEqual("o", Configuration.Default.DateTimeFormat); + } - [Test ()] - public void TestDateTimeFormat_UType() - { - Configuration.Default.DateTimeFormat = "u"; + [Test ()] + public void TestDateTimeFormat_UType() + { + Configuration.Default.DateTimeFormat = "u"; - Assert.AreEqual("u", Configuration.Default.DateTimeFormat); - } + Assert.AreEqual("u", Configuration.Default.DateTimeFormat); + } [Test ()] public void TestConstructor() @@ -64,7 +68,7 @@ namespace SwaggerClientTest.TestConfiguration } - [Test ()] + [Test ()] public void TestDefautlConfiguration () { PetApi p1 = new PetApi (); @@ -110,14 +114,16 @@ namespace SwaggerClientTest.TestConfiguration [Test ()] public void TestTimeout () { - Configuration c1 = new Configuration(); - Assert.AreEqual(100000, c1.Timeout); // default vaue + Configuration c1 = new Configuration (); + Assert.AreEqual (100000, c1.Timeout); // default vaue c1.Timeout = 50000; - Assert.AreEqual(50000, c1.Timeout); + Assert.AreEqual (50000, c1.Timeout); - Configuration c2 = new Configuration(timeout: 20000); - Assert.AreEqual(20000, c2.Timeout); + Configuration c2 = new Configuration (timeout: 20000); + Assert.AreEqual (20000, c2.Timeout); } + } -} \ No newline at end of file +} + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 743b0b97853..5660f132a37 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -1,5 +1,26 @@ - + + Debug AnyCPU @@ -38,36 +59,38 @@ - $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll - $(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll - ..\packages\NUnit.2.6.3\lib\nunit.framework.dll - ..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll - ..\..\vendor\NUnit.2.6.3\lib\nunit.framework.dll + $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\vendor\NUnit.3.2.1\lib\nunit.framework.dll - + - + - - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} - IO.Swagger - + + {85AE8212-9819-4224-A9E5-B93419EC927B} + IO.Swagger + + + + - diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..b4680801e4c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs @@ -0,0 +1,56 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing AdditionalPropertiesClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class AdditionalPropertiesClassTests + { + private AdditionalPropertiesClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new AdditionalPropertiesClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of AdditionalPropertiesClass + /// + [Test] + public void AdditionalPropertiesClassInstanceTest() + { + Assert.IsInstanceOfType(typeof(AdditionalPropertiesClass), instance, "instance is a AdditionalPropertiesClass"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs index 5baa4d93485..6e824fbfd84 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void AnimalFarmInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a AnimalFarm"); + Assert.IsInstanceOfType(typeof(AnimalFarm), instance, "instance is a AnimalFarm"); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs index 861ca5fe026..59cd4d76d68 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Test [SetUp] public void Init() { - instance = new Animal(); + instance = new Animal(ClassName: "csharp test"); } /// @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void AnimalInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Animal"); + Assert.IsInstanceOfType(typeof(Animal), instance, "instance is a Animal"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs index c2535cdadb3..13d4310916b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ApiResponseInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ApiResponse"); + Assert.IsInstanceOfType(typeof(ApiResponse), instance, "instance is a ApiResponse"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs new file mode 100644 index 00000000000..c063340171f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs @@ -0,0 +1,56 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ArrayTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayTestTests + { + private ArrayTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new ArrayTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayTest + /// + [Test] + public void ArrayTestInstanceTest() + { + Assert.IsInstanceOfType(typeof(ArrayTest), instance, "instance is a ArrayTest"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs index 15cc1ab22de..8a6abb12f62 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Test [SetUp] public void Init() { - instance = new Cat(); + instance = new Cat(ClassName: "csharp test"); } /// @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void CatInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Cat"); + Assert.IsInstanceOfType(typeof(Cat), instance, "instance is a Cat"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs index 96e5d946c0b..3c7ba0499aa 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void CategoryInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Category"); + Assert.IsInstanceOfType(typeof(Category), instance, "instance is a Category"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs index 33aa6cb51af..5d3b6fef175 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Test [SetUp] public void Init() { - instance = new Dog(); + instance = new Dog(ClassName: "csharp test"); } /// @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void DogInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Dog"); + Assert.IsInstanceOfType(typeof(Dog), instance, "instance is a Dog"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs index 8c81c81fbb1..154e3c7b57a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs @@ -47,9 +47,25 @@ namespace IO.Swagger.Test [Test] public void EnumClassInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a EnumClass"); + Assert.IsInstanceOfType(typeof(EnumClass), instance, "instance is a EnumClass"); } + /// + /// Test EnumClass + /// + [Test] + public void EnumClassValueTest () + { + // test serialization for string + Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumClass.Abc), "\"_abc\""); + + // test serialization for number + Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1), "\"-1\""); + + // test cast to int + Assert.AreEqual ((int)EnumTest.EnumIntegerEnum.NUMBER_MINUS_1, -1); + + } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs index 2679b085233..9ea929a0cd6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void EnumTestInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a EnumTest"); + Assert.IsInstanceOfType(typeof(EnumTest), instance, "instance is a EnumTest"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs index 7676fcae9b9..1d2d334a45e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Test [SetUp] public void Init() { - instance = new FormatTest(); + instance = new FormatTest(Number: 123, _Byte: new byte[] { 0x20 }, Date: new DateTime(2015, 1, 18), Password: "xyz"); } /// @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void FormatTestInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a FormatTest"); + Assert.IsInstanceOfType(typeof(FormatTest), instance, "instance is a FormatTest"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..2157758ec1f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -0,0 +1,72 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing MixedPropertiesAndAdditionalPropertiesClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class MixedPropertiesAndAdditionalPropertiesClassTests + { + private MixedPropertiesAndAdditionalPropertiesClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass + /// + [Test] + public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() + { + Assert.IsInstanceOfType(typeof(MixedPropertiesAndAdditionalPropertiesClass), instance, "instance is a MixedPropertiesAndAdditionalPropertiesClass"); + } + + /// + /// Test the property 'Uuid' + /// + [Test] + public void UuidTest() + { + // TODO: unit test for the property 'Uuid' + } + /// + /// Test the property 'DateTime' + /// + [Test] + public void DateTimeTest() + { + // TODO: unit test for the property 'DateTime' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs index eb55902a998..13bbc1b1c7d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void Model200ResponseInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Model200Response"); + Assert.IsInstanceOfType(typeof(Model200Response), instance, "instance is a Model200Response"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs index 1c620b73241..53e62fc51a3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ModelReturnInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ModelReturn"); + Assert.IsInstanceOfType(typeof(ModelReturn), instance, "instance is a ModelReturn"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs index c6c68253ca0..d1e0deec41f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Test [SetUp] public void Init() { - instance = new Name(); + instance = new Name(_Name: 1, Property: "csharp"); } /// @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void NameInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Name"); + Assert.IsInstanceOfType(typeof(Name), instance, "instance is a Name"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs index 9363c7409e4..799b6ef43f8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs @@ -41,13 +41,23 @@ namespace IO.Swagger.Test } + /// + /// Test creating a new instance of Order + /// + [Test ()] + public void TestNewOrder() + { + Order o = new Order (); + Assert.IsNull (o.Id); + } + /// /// Test an instance of Order /// [Test] public void OrderInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Order"); + Assert.IsInstanceOfType(typeof(Order), instance, "instance is a Order"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs index d016d3500a4..7029264ee06 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs @@ -23,13 +23,15 @@ namespace IO.Swagger.Test { private Pet instance; + private long petId = 11088; + /// /// Setup before each test /// [SetUp] public void Init() { - instance = new Pet(); + instance = new Pet(Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test" }); } /// @@ -47,7 +49,7 @@ namespace IO.Swagger.Test [Test] public void PetInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), instance, "instance is a Pet"); } /// @@ -99,6 +101,69 @@ namespace IO.Swagger.Test // TODO: unit test for the property 'Status' } + /// + /// Test Equal + /// + [Test ()] + public void TestEqual() + { + // create pet + Pet p1 = new Pet (Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test" }); + p1.Id = petId; + //p1.Name = "Csharp test"; + p1.Status = Pet.StatusEnum.Available; + // create Category object + Category category1 = new Category (); + category1.Id = 56; + category1.Name = "sample category name2"; + List photoUrls1 = new List (new String[] { "sample photoUrls" }); + // create Tag object + Tag tag1 = new Tag (); + tag1.Id = petId; + tag1.Name = "csharp sample tag name1"; + List tags1 = new List (new Tag[] { tag1 }); + p1.Tags = tags1; + p1.Category = category1; + p1.PhotoUrls = photoUrls1; + + // create pet 2 + Pet p2 = new Pet (Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test" }); + p2.Id = petId; + p2.Name = "Csharp test"; + p2.Status = Pet.StatusEnum.Available; + // create Category object + Category category2 = new Category (); + category2.Id = 56; + category2.Name = "sample category name2"; + List photoUrls2 = new List (new String[] { "sample photoUrls" }); + // create Tag object + Tag tag2 = new Tag (); + tag2.Id = petId; + tag2.Name = "csharp sample tag name1"; + List tags2 = new List (new Tag[] { tag2 }); + p2.Tags = tags2; + p2.Category = category2; + p2.PhotoUrls = photoUrls2; + + // p1 and p2 should be equal (both object and attribute level) + Assert.IsTrue (category1.Equals (category2)); + Assert.IsTrue (tags1.SequenceEqual (tags2)); + Assert.IsTrue (p1.PhotoUrls.SequenceEqual (p2.PhotoUrls)); + + Assert.IsTrue (p1.Equals (p2)); + + // update attribute to that p1 and p2 are not equal + category2.Name = "new category name"; + Assert.IsFalse (category1.Equals (category2)); + + tags2 = new List (); + Assert.IsFalse (tags1.SequenceEqual (tags2)); + + // photoUrls has not changed so it should be equal + Assert.IsTrue (p1.PhotoUrls.SequenceEqual (p2.PhotoUrls)); + + Assert.IsFalse (p1.Equals (p2)); + } } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 00000000000..e0c4029546b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs @@ -0,0 +1,72 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ReadOnlyFirst + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ReadOnlyFirstTests + { + private ReadOnlyFirst instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new ReadOnlyFirst(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ReadOnlyFirst + /// + [Test] + public void ReadOnlyFirstInstanceTest() + { + Assert.IsInstanceOfType(typeof(ReadOnlyFirst), instance, "instance is a ReadOnlyFirst"); + } + + /// + /// Test the property 'Bar' + /// + [Test] + public void BarTest() + { + // TODO: unit test for the property 'Bar' + } + /// + /// Test the property 'Baz' + /// + [Test] + public void BazTest() + { + // TODO: unit test for the property 'Baz' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs index 21051e71f54..eec6e837449 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void SpecialModelNameInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a SpecialModelName"); + Assert.IsInstanceOfType(typeof(SpecialModelName), instance, "instance is a SpecialModelName"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs index 4fff0e4c12d..2b78594eb6f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void TagInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Tag"); + Assert.IsInstanceOfType(typeof(Tag), instance, "instance is a Tag"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs index 38f2667c403..59451079ebf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void UserInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a User"); + Assert.IsInstanceOfType(typeof(User), instance, "instance is a User"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config index a8a3491f63d..317248179b6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config @@ -1,6 +1,6 @@ - + - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/swagger-logo.png similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/swagger-logo.png diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs index 8b9fe2e52c8..973771809a2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -10,7 +32,7 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface IFakeApi + public interface IFakeApi : IApiAccessor { #region Synchronous Operations /// @@ -33,7 +55,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// - void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -55,7 +77,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); #endregion Synchronous Operations #region Asynchronous Operations /// @@ -78,7 +100,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -100,15 +122,17 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); #endregion Asynchronous Operations } /// /// Represents a collection of functions to interact with the API endpoints /// - public class FakeApi : IFakeApi + public partial class FakeApi : IFakeApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -117,6 +141,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -137,6 +163,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -157,7 +185,7 @@ namespace IO.Swagger.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing @@ -169,6 +197,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -208,7 +252,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// - public void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { TestEndpointParametersWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } @@ -230,7 +274,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// ApiResponse of Object(void) - public ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -255,13 +299,15 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { + "application/xml; charset=utf-8", + "application/json; charset=utf-8" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { - "application/xml", - "application/json" + "application/xml; charset=utf-8", + "application/json; charset=utf-8" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) @@ -291,10 +337,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEndpointParameters", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -319,7 +366,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { await TestEndpointParametersAsyncWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -342,7 +389,7 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -367,13 +414,15 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { + "application/xml; charset=utf-8", + "application/json; charset=utf-8" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { - "application/xml", - "application/json" + "application/xml; charset=utf-8", + "application/json; charset=utf-8" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) @@ -403,10 +452,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEndpointParameters", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs index ada1bcbed30..abf5a0595b2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -11,7 +33,7 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface IPetApi + public interface IPetApi : IApiAccessor { #region Synchronous Operations /// @@ -378,8 +400,10 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class PetApi : IPetApi + public partial class PetApi : IPetApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -388,6 +412,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -408,6 +434,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -428,7 +456,7 @@ namespace IO.Swagger.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing @@ -440,6 +468,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -535,10 +579,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("AddPet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -620,10 +665,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("AddPet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -698,10 +744,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeletePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -777,10 +824,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeletePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -853,10 +901,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByStatus", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -930,10 +979,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByStatus", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1006,10 +1056,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByTags", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1083,10 +1134,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByTags", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1159,10 +1211,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetPetById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1235,10 +1288,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetPetById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1319,10 +1373,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1404,10 +1459,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1486,10 +1542,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1569,10 +1626,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1651,10 +1709,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UploadFile", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1734,10 +1793,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UploadFile", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs index bbe6343ee84..3fbbe71b8ca 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -11,7 +33,7 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface IStoreApi + public interface IStoreApi : IApiAccessor { #region Synchronous Operations /// @@ -186,8 +208,10 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class StoreApi : IStoreApi + public partial class StoreApi : IStoreApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -196,6 +220,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -216,6 +242,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -236,7 +264,7 @@ namespace IO.Swagger.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing @@ -248,6 +276,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -328,10 +372,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -398,10 +443,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -467,10 +513,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetInventory", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -536,10 +583,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetInventory", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -606,10 +654,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetOrderById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -677,10 +726,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetOrderById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -754,10 +804,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("PlaceOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -832,10 +883,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("PlaceOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs index f4b36e47e32..6fb6244264e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -11,7 +33,7 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface IUserApi + public interface IUserApi : IApiAccessor { #region Synchronous Operations /// @@ -362,8 +384,10 @@ namespace IO.Swagger.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class UserApi : IUserApi + public partial class UserApi : IUserApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -372,6 +396,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -392,6 +418,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -412,7 +440,7 @@ namespace IO.Swagger.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing @@ -424,6 +452,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -511,10 +555,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -588,10 +633,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -664,10 +710,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -741,10 +788,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -817,10 +865,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -894,10 +943,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -963,10 +1013,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1033,10 +1084,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1103,10 +1155,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetUserByName", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1174,10 +1227,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetUserByName", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1250,10 +1304,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LoginUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1327,10 +1382,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LoginUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1390,10 +1446,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LogoutUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1454,10 +1511,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LogoutUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1536,10 +1594,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1619,10 +1678,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs index 42299503d2a..c5a2de83da1 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections; using System.Collections.Generic; @@ -14,10 +36,28 @@ using RestSharp; namespace IO.Swagger.Client { /// - /// API client is mainly responible for making the HTTP call to the API backend. + /// API client is mainly responsible for making the HTTP call to the API backend. /// - public class ApiClient + public partial class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + /// /// Initializes a new instance of the class /// with default configuration and base path (http://petstore.swagger.io/v2). @@ -150,7 +190,10 @@ namespace IO.Swagger.Client // set user agent RestClient.UserAgent = Configuration.UserAgent; + InterceptRequest(request); var response = RestClient.Execute(request); + InterceptResponse(request, response); + return (Object) response; } /// @@ -175,7 +218,9 @@ namespace IO.Swagger.Client var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); + InterceptResponse(request, response); return (Object)response; } @@ -289,7 +334,7 @@ namespace IO.Swagger.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs index 7b7a11721df..a19a664112f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; namespace IO.Swagger.Client diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs index 808837b4aa1..6c6134c114a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index acbaee1e688..533b994dab2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Reflection; using System.Collections.Generic; @@ -79,6 +101,17 @@ namespace IO.Swagger.Client /// Configuration. public static Configuration Default = new Configuration(); + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + int status = (int) response.StatusCode; + if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); + if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + return null; + }; + /// /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..579cb8618c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs @@ -0,0 +1,36 @@ +/* + * 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 + * + * 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. + */ + + +using System; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs new file mode 100644 index 00000000000..65ff8bef73b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs @@ -0,0 +1,54 @@ +/* + * 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 + * + * 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. + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index ad86456ecea..7a78c9e7e69 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -1,9 +1,30 @@ + Debug AnyCPU - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + {BF42B49D-37A0-49C4-A405-24CD946ADAA7} Library Properties Swagger Library @@ -38,10 +59,10 @@ - $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - ..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs new file mode 100644 index 00000000000..db9ac4006b7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -0,0 +1,141 @@ +/* + * 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 + * + * 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. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// AdditionalPropertiesClass + /// + [DataContract] + public partial class AdditionalPropertiesClass : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// MapProperty. + /// MapOfMapProperty. + public AdditionalPropertiesClass(Dictionary MapProperty = null, Dictionary> MapOfMapProperty = null) + { + this.MapProperty = MapProperty; + this.MapOfMapProperty = MapOfMapProperty; + } + + /// + /// Gets or Sets MapProperty + /// + [DataMember(Name="map_property", EmitDefaultValue=false)] + public Dictionary MapProperty { get; set; } + /// + /// Gets or Sets MapOfMapProperty + /// + [DataMember(Name="map_of_map_property", EmitDefaultValue=false)] + public Dictionary> MapOfMapProperty { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as AdditionalPropertiesClass); + } + + /// + /// Returns true if AdditionalPropertiesClass instances are equal + /// + /// Instance of AdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(AdditionalPropertiesClass other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.MapProperty == other.MapProperty || + this.MapProperty != null && + this.MapProperty.SequenceEqual(other.MapProperty) + ) && + ( + this.MapOfMapProperty == other.MapOfMapProperty || + this.MapOfMapProperty != null && + this.MapOfMapProperty.SequenceEqual(other.MapOfMapProperty) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.MapProperty != null) + hash = hash * 59 + this.MapProperty.GetHashCode(); + if (this.MapOfMapProperty != null) + hash = hash * 59 + this.MapOfMapProperty.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index 87a17aa4fae..5d8417c74a3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -17,6 +39,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Animal : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() { } /// /// Initializes a new instance of the class. /// @@ -33,8 +60,6 @@ namespace IO.Swagger.Model { this.ClassName = ClassName; } - - // use default value if no "Color" provided if (Color == null) { @@ -44,7 +69,6 @@ namespace IO.Swagger.Model { this.Color = Color; } - } /// @@ -66,7 +90,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); -sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs index 76685fe8495..267ab5f4017 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -22,8 +44,6 @@ namespace IO.Swagger.Model /// public AnimalFarm() { - - } /// @@ -34,7 +54,7 @@ namespace IO.Swagger.Model { var sb = new StringBuilder(); sb.Append("class AnimalFarm {\n"); - sb.Append("}\n"); + sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs index 8a0f40369fb..0543e709b29 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -25,14 +47,9 @@ namespace IO.Swagger.Model /// Message. public ApiResponse(int? Code = null, string Type = null, string Message = null) { - - - this.Code = Code; - - this.Type = Type; - - this.Message = Message; - + this.Code = Code; + this.Type = Type; + this.Message = Message; } /// @@ -59,8 +76,8 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); -sb.Append(" Type: ").Append(Type).Append("\n"); -sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs new file mode 100644 index 00000000000..b80118c790f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs @@ -0,0 +1,156 @@ +/* + * 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 + * + * 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. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// ArrayTest + /// + [DataContract] + public partial class ArrayTest : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayOfString. + /// ArrayArrayOfInteger. + /// ArrayArrayOfModel. + public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null) + { + this.ArrayOfString = ArrayOfString; + this.ArrayArrayOfInteger = ArrayArrayOfInteger; + this.ArrayArrayOfModel = ArrayArrayOfModel; + } + + /// + /// Gets or Sets ArrayOfString + /// + [DataMember(Name="array_of_string", EmitDefaultValue=false)] + public List ArrayOfString { get; set; } + /// + /// Gets or Sets ArrayArrayOfInteger + /// + [DataMember(Name="array_array_of_integer", EmitDefaultValue=false)] + public List> ArrayArrayOfInteger { get; set; } + /// + /// Gets or Sets ArrayArrayOfModel + /// + [DataMember(Name="array_array_of_model", EmitDefaultValue=false)] + public List> ArrayArrayOfModel { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ArrayTest {\n"); + sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); + sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); + sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ArrayTest); + } + + /// + /// Returns true if ArrayTest instances are equal + /// + /// Instance of ArrayTest to be compared + /// Boolean + public bool Equals(ArrayTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ArrayOfString == other.ArrayOfString || + this.ArrayOfString != null && + this.ArrayOfString.SequenceEqual(other.ArrayOfString) + ) && + ( + this.ArrayArrayOfInteger == other.ArrayArrayOfInteger || + this.ArrayArrayOfInteger != null && + this.ArrayArrayOfInteger.SequenceEqual(other.ArrayArrayOfInteger) + ) && + ( + this.ArrayArrayOfModel == other.ArrayArrayOfModel || + this.ArrayArrayOfModel != null && + this.ArrayArrayOfModel.SequenceEqual(other.ArrayArrayOfModel) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ArrayOfString != null) + hash = hash * 59 + this.ArrayOfString.GetHashCode(); + if (this.ArrayArrayOfInteger != null) + hash = hash * 59 + this.ArrayArrayOfInteger.GetHashCode(); + if (this.ArrayArrayOfModel != null) + hash = hash * 59 + this.ArrayArrayOfModel.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index fee880c5d82..f288be939c4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -17,6 +39,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Cat : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() { } /// /// Initializes a new instance of the class. /// @@ -34,8 +61,6 @@ namespace IO.Swagger.Model { this.ClassName = ClassName; } - - // use default value if no "Color" provided if (Color == null) { @@ -45,9 +70,7 @@ namespace IO.Swagger.Model { this.Color = Color; } - - this.Declawed = Declawed; - + this.Declawed = Declawed; } /// @@ -74,8 +97,8 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); -sb.Append(" Color: ").Append(Color).Append("\n"); -sb.Append(" Declawed: ").Append(Declawed).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs index 51a3f971b38..be9d35a9fb7 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -24,12 +46,8 @@ namespace IO.Swagger.Model /// Name. public Category(long? Id = null, string Name = null) { - - - this.Id = Id; - - this.Name = Name; - + this.Id = Id; + this.Name = Name; } /// @@ -51,7 +69,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); -sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index fb65e3e0c99..000b1f1bec9 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -17,6 +39,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Dog : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() { } /// /// Initializes a new instance of the class. /// @@ -34,8 +61,6 @@ namespace IO.Swagger.Model { this.ClassName = ClassName; } - - // use default value if no "Color" provided if (Color == null) { @@ -45,9 +70,7 @@ namespace IO.Swagger.Model { this.Color = Color; } - - this.Breed = Breed; - + this.Breed = Breed; } /// @@ -74,8 +97,8 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); -sb.Append(" Color: ").Append(Color).Append("\n"); -sb.Append(" Breed: ").Append(Breed).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs index 1fb5f0b6626..3ce229e2efd 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs index f8bebd6b2d7..2725d9d17a4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -100,14 +122,9 @@ namespace IO.Swagger.Model /// EnumNumber. public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) { - - - this.EnumString = EnumString; - - this.EnumInteger = EnumInteger; - - this.EnumNumber = EnumNumber; - + this.EnumString = EnumString; + this.EnumInteger = EnumInteger; + this.EnumNumber = EnumNumber; } /// @@ -119,8 +136,8 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); -sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); -sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); + sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index 33301f02a95..5e50732ee0b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -17,6 +39,11 @@ namespace IO.Swagger.Model [DataContract] public partial class FormatTest : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() { } /// /// Initializes a new instance of the class. /// @@ -33,7 +60,7 @@ namespace IO.Swagger.Model /// DateTime. /// Uuid. /// Password (required). - public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, double? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) + public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) { // to ensure "Number" is required (not null) if (Number == null) @@ -71,26 +98,15 @@ namespace IO.Swagger.Model { this.Password = Password; } - - - this.Integer = Integer; - - this.Int32 = Int32; - - this.Int64 = Int64; - - this._Float = _Float; - - this._Double = _Double; - - this._String = _String; - - this.Binary = Binary; - - this.DateTime = DateTime; - - this.Uuid = Uuid; - + this.Integer = Integer; + this.Int32 = Int32; + this.Int64 = Int64; + this._Float = _Float; + this._Double = _Double; + this._String = _String; + this.Binary = Binary; + this.DateTime = DateTime; + this.Uuid = Uuid; } /// @@ -112,7 +128,7 @@ namespace IO.Swagger.Model /// Gets or Sets Number /// [DataMember(Name="number", EmitDefaultValue=false)] - public double? Number { get; set; } + public decimal? Number { get; set; } /// /// Gets or Sets _Float /// @@ -167,18 +183,18 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); -sb.Append(" Int32: ").Append(Int32).Append("\n"); -sb.Append(" Int64: ").Append(Int64).Append("\n"); -sb.Append(" Number: ").Append(Number).Append("\n"); -sb.Append(" _Float: ").Append(_Float).Append("\n"); -sb.Append(" _Double: ").Append(_Double).Append("\n"); -sb.Append(" _String: ").Append(_String).Append("\n"); -sb.Append(" _Byte: ").Append(_Byte).Append("\n"); -sb.Append(" Binary: ").Append(Binary).Append("\n"); -sb.Append(" Date: ").Append(Date).Append("\n"); -sb.Append(" DateTime: ").Append(DateTime).Append("\n"); -sb.Append(" Uuid: ").Append(Uuid).Append("\n"); -sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Int32: ").Append(Int32).Append("\n"); + sb.Append(" Int64: ").Append(Int64).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" _Float: ").Append(_Float).Append("\n"); + sb.Append(" _Double: ").Append(_Double).Append("\n"); + sb.Append(" _String: ").Append(_String).Append("\n"); + sb.Append(" _Byte: ").Append(_Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 00000000000..ea20988a1ec --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -0,0 +1,156 @@ +/* + * 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 + * + * 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. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + [DataContract] + public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// Uuid. + /// DateTime. + /// Map. + public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = null, DateTime? DateTime = null, Dictionary Map = null) + { + this.Uuid = Uuid; + this.DateTime = DateTime; + this.Map = Map; + } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name="uuid", EmitDefaultValue=false)] + public Guid? Uuid { get; set; } + /// + /// Gets or Sets DateTime + /// + [DataMember(Name="dateTime", EmitDefaultValue=false)] + public DateTime? DateTime { get; set; } + /// + /// Gets or Sets Map + /// + [DataMember(Name="map", EmitDefaultValue=false)] + public Dictionary Map { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as MixedPropertiesAndAdditionalPropertiesClass); + } + + /// + /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal + /// + /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(MixedPropertiesAndAdditionalPropertiesClass other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Uuid == other.Uuid || + this.Uuid != null && + this.Uuid.Equals(other.Uuid) + ) && + ( + this.DateTime == other.DateTime || + this.DateTime != null && + this.DateTime.Equals(other.DateTime) + ) && + ( + this.Map == other.Map || + this.Map != null && + this.Map.SequenceEqual(other.Map) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Uuid != null) + hash = hash * 59 + this.Uuid.GetHashCode(); + if (this.DateTime != null) + hash = hash * 59 + this.DateTime.GetHashCode(); + if (this.Map != null) + hash = hash * 59 + this.Map.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs index cec5ee75e2f..7e6d1c79a16 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -23,10 +45,7 @@ namespace IO.Swagger.Model /// Name. public Model200Response(int? Name = null) { - - - this.Name = Name; - + this.Name = Name; } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs index 3cfa6c0a77e..e6255f285ee 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -23,10 +45,7 @@ namespace IO.Swagger.Model /// _Return. public ModelReturn(int? _Return = null) { - - - this._Return = _Return; - + this._Return = _Return; } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index 25273ffb97b..1c1b771f53b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -17,6 +39,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Name : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() { } /// /// Initializes a new instance of the class. /// @@ -33,10 +60,7 @@ namespace IO.Swagger.Model { this._Name = _Name; } - - - this.Property = Property; - + this.Property = Property; } /// @@ -68,9 +92,9 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); -sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); -sb.Append(" Property: ").Append(Property).Append("\n"); -sb.Append(" _123Number: ").Append(_123Number).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); + sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" _123Number: ").Append(_123Number).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs index 652128a33a1..33f1b2d99da 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -61,18 +83,11 @@ namespace IO.Swagger.Model /// Complete (default to false). public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, StatusEnum? Status = null, bool? Complete = null) { - - - this.Id = Id; - - this.PetId = PetId; - - this.Quantity = Quantity; - - this.ShipDate = ShipDate; - - this.Status = Status; - + this.Id = Id; + this.PetId = PetId; + this.Quantity = Quantity; + this.ShipDate = ShipDate; + this.Status = Status; // use default value if no "Complete" provided if (Complete == null) { @@ -82,7 +97,6 @@ namespace IO.Swagger.Model { this.Complete = Complete; } - } /// @@ -119,11 +133,11 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); -sb.Append(" PetId: ").Append(PetId).Append("\n"); -sb.Append(" Quantity: ").Append(Quantity).Append("\n"); -sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); -sb.Append(" Status: ").Append(Status).Append("\n"); -sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs index 420ab138b07..7db2644307a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -53,6 +75,11 @@ namespace IO.Swagger.Model /// /// Initializes a new instance of the class. /// + [JsonConstructorAttribute] + protected Pet() { } + /// + /// Initializes a new instance of the class. + /// /// Id. /// Category. /// Name (required). @@ -79,16 +106,10 @@ namespace IO.Swagger.Model { this.PhotoUrls = PhotoUrls; } - - - this.Id = Id; - - this.Category = Category; - - this.Tags = Tags; - - this.Status = Status; - + this.Id = Id; + this.Category = Category; + this.Tags = Tags; + this.Status = Status; } /// @@ -125,11 +146,11 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); -sb.Append(" Category: ").Append(Category).Append("\n"); -sb.Append(" Name: ").Append(Name).Append("\n"); -sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); -sb.Append(" Tags: ").Append(Tags).Append("\n"); -sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs new file mode 100644 index 00000000000..422c7671139 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -0,0 +1,139 @@ +/* + * 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 + * + * 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. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// ReadOnlyFirst + /// + [DataContract] + public partial class ReadOnlyFirst : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// Baz. + public ReadOnlyFirst(string Baz = null) + { + this.Baz = Baz; + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name="bar", EmitDefaultValue=false)] + public string Bar { get; private set; } + /// + /// Gets or Sets Baz + /// + [DataMember(Name="baz", EmitDefaultValue=false)] + public string Baz { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ReadOnlyFirst {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Baz: ").Append(Baz).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ReadOnlyFirst); + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Bar == other.Bar || + this.Bar != null && + this.Bar.Equals(other.Bar) + ) && + ( + this.Baz == other.Baz || + this.Baz != null && + this.Baz.Equals(other.Baz) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Bar != null) + hash = hash * 59 + this.Bar.GetHashCode(); + if (this.Baz != null) + hash = hash * 59 + this.Baz.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs index 68a92724b1f..82cde053d0b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -23,10 +45,7 @@ namespace IO.Swagger.Model /// SpecialPropertyName. public SpecialModelName(long? SpecialPropertyName = null) { - - - this.SpecialPropertyName = SpecialPropertyName; - + this.SpecialPropertyName = SpecialPropertyName; } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs index ffb42e09df9..93b7b66c005 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -24,12 +46,8 @@ namespace IO.Swagger.Model /// Name. public Tag(long? Id = null, string Name = null) { - - - this.Id = Id; - - this.Name = Name; - + this.Id = Id; + this.Name = Name; } /// @@ -51,7 +69,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); -sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs index 3931afbf0f8..34e60b081b4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs @@ -1,3 +1,25 @@ +/* + * 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 + * + * 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. + */ + using System; using System.Linq; using System.IO; @@ -30,24 +52,14 @@ namespace IO.Swagger.Model /// User Status. public User(long? Id = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) { - - - this.Id = Id; - - this.Username = Username; - - this.FirstName = FirstName; - - this.LastName = LastName; - - this.Email = Email; - - this.Password = Password; - - this.Phone = Phone; - - this.UserStatus = UserStatus; - + this.Id = Id; + this.Username = Username; + this.FirstName = FirstName; + this.LastName = LastName; + this.Email = Email; + this.Password = Password; + this.Phone = Phone; + this.UserStatus = UserStatus; } /// @@ -100,13 +112,13 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); -sb.Append(" Username: ").Append(Username).Append("\n"); -sb.Append(" FirstName: ").Append(FirstName).Append("\n"); -sb.Append(" LastName: ").Append(LastName).Append("\n"); -sb.Append(" Email: ").Append(Email).Append("\n"); -sb.Append(" Password: ").Append(Password).Append("\n"); -sb.Append(" Phone: ").Append(Phone).Append("\n"); -sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config index 91f17cd0819..80f617d6d9f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config @@ -1,5 +1,5 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FakeApi.md deleted file mode 100644 index ae9fd8c3d36..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FakeApi.md +++ /dev/null @@ -1,91 +0,0 @@ -# IO.Swagger.Api.FakeApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters - - -# **TestEndpointParameters** -> void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) - -Fake endpoint for testing various parameters - -Fake endpoint for testing various parameters - -### Example -```csharp -using System; -using System.Diagnostics; -using IO.Swagger.Api; -using IO.Swagger.Client; -using IO.Swagger.Model; - -namespace Example -{ - public class TestEndpointParametersExample - { - public void main() - { - - var apiInstance = new FakeApi(); - var number = 3.4; // double? | None - var _double = 1.2; // double? | None - var _string = _string_example; // string | None - var _byte = B; // byte[] | None - var integer = 56; // int? | None (optional) - var int32 = 56; // int? | None (optional) - var int64 = 789; // long? | None (optional) - var _float = 3.4; // float? | None (optional) - var binary = B; // byte[] | None (optional) - var date = 2013-10-20; // DateTime? | None (optional) - var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) - var password = password_example; // string | None (optional) - - try - { - // Fake endpoint for testing various parameters - apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - catch (Exception e) - { - Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message ); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **double?**| None | - **_double** | **double?**| None | - **_string** | **string**| None | - **_byte** | **byte[]**| None | - **integer** | **int?**| None | [optional] - **int32** | **int?**| None | [optional] - **int64** | **long?**| None | [optional] - **_float** | **float?**| None | [optional] - **binary** | **byte[]**| None | [optional] - **date** | **DateTime?**| None | [optional] - **dateTime** | **DateTime?**| None | [optional] - **password** | **string**| None | [optional] - -### Return type - -void (empty response body) - -### 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) - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/FakeApi.cs deleted file mode 100644 index 1c92dc3bbda..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/FakeApi.cs +++ /dev/null @@ -1,418 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using RestSharp; -using IO.Swagger.Client; - -namespace IO.Swagger.Api -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public interface IFakeApi - { - #region Synchronous Operations - /// - /// Fake endpoint for testing various parameters - /// - /// - /// Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// - void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); - - /// - /// Fake endpoint for testing various parameters - /// - /// - /// Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); - #endregion Synchronous Operations - #region Asynchronous Operations - /// - /// Fake endpoint for testing various parameters - /// - /// - /// Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); - - /// - /// Fake endpoint for testing various parameters - /// - /// - /// Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); - #endregion Asynchronous Operations - } - - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class FakeApi : IFakeApi - { - /// - /// Initializes a new instance of the class. - /// - /// - public FakeApi(String basePath) - { - this.Configuration = new Configuration(new ApiClient(basePath)); - - // ensure API client has configuration ready - if (Configuration.ApiClient.Configuration == null) - { - this.Configuration.ApiClient.Configuration = this.Configuration; - } - } - - /// - /// Initializes a new instance of the class - /// using Configuration object - /// - /// An instance of Configuration - /// - public FakeApi(Configuration configuration = null) - { - if (configuration == null) // use the default one in Configuration - this.Configuration = Configuration.Default; - else - this.Configuration = configuration; - - // ensure API client has configuration ready - if (Configuration.ApiClient.Configuration == null) - { - this.Configuration.ApiClient.Configuration = this.Configuration; - } - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - public String GetBasePath() - { - return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] - public void SetBasePath(String basePath) - { - // do nothing - } - - /// - /// Gets or sets the configuration object - /// - /// An instance of the Configuration - public Configuration Configuration {get; set;} - - /// - /// Gets the default header. - /// - /// Dictionary of HTTP header - [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] - public Dictionary DefaultHeader() - { - return this.Configuration.DefaultHeader; - } - - /// - /// Add default header. - /// - /// Header field name. - /// Header field value. - /// - [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] - public void AddDefaultHeader(string key, string value) - { - this.Configuration.AddDefaultHeader(key, value); - } - - /// - /// Fake endpoint for testing various parameters Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// - public void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) - { - TestEndpointParametersWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /// - /// Fake endpoint for testing various parameters Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// ApiResponse of Object(void) - public ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) - { - // verify the required parameter 'number' is set - if (number == null) - throw new ApiException(400, "Missing required parameter 'number' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_double' is set - if (_double == null) - throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_string' is set - if (_string == null) - throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_byte' is set - if (_byte == null) - throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); - - var localVarPath = "/fake"; - var localVarPathParams = new Dictionary(); - var localVarQueryParams = new Dictionary(); - var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); - var localVarFormParams = new Dictionary(); - var localVarFileParams = new Dictionary(); - Object localVarPostBody = null; - - // to determine the Content-Type header - String[] localVarHttpContentTypes = new String[] { - }; - String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); - - // to determine the Accept header - String[] localVarHttpHeaderAccepts = new String[] { - "application/xml", - "application/json" - }; - String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); - if (localVarHttpHeaderAccept != null) - localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - - // set "format" to json by default - // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json - localVarPathParams.Add("format", "json"); - if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter - if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter - if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter - if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter - if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter - if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter - if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter - if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter - if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter - if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter - if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter - if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter - - - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, - localVarPathParams, localVarHttpContentType); - - int localVarStatusCode = (int) localVarResponse.StatusCode; - - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - null); - } - - /// - /// Fake endpoint for testing various parameters Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) - { - await TestEndpointParametersAsyncWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - - } - - /// - /// Fake endpoint for testing various parameters Fake endpoint for testing various parameters - /// - /// Thrown when fails to make API call - /// None - /// None - /// None - /// None - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// None (optional) - /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) - { - // verify the required parameter 'number' is set - if (number == null) - throw new ApiException(400, "Missing required parameter 'number' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_double' is set - if (_double == null) - throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_string' is set - if (_string == null) - throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_byte' is set - if (_byte == null) - throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); - - var localVarPath = "/fake"; - var localVarPathParams = new Dictionary(); - var localVarQueryParams = new Dictionary(); - var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); - var localVarFormParams = new Dictionary(); - var localVarFileParams = new Dictionary(); - Object localVarPostBody = null; - - // to determine the Content-Type header - String[] localVarHttpContentTypes = new String[] { - }; - String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); - - // to determine the Accept header - String[] localVarHttpHeaderAccepts = new String[] { - "application/xml", - "application/json" - }; - String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); - if (localVarHttpHeaderAccept != null) - localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - - // set "format" to json by default - // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json - localVarPathParams.Add("format", "json"); - if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter - if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter - if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter - if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter - if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter - if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter - if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter - if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter - if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter - if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter - if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter - if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter - - - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, - localVarPathParams, localVarHttpContentType); - - int localVarStatusCode = (int) localVarResponse.StatusCode; - - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - null); - } - - } -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/CatDogTest.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/CatDogTest.cs deleted file mode 100644 index 7868fef3f39..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/CatDogTest.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.Serialization; -using Newtonsoft.Json; - -namespace IO.Swagger.Model -{ - - /// - /// - /// - [DataContract] - public class CatDogTest : Cat, IEquatable - { - /// - /// Initializes a new instance of the class. - /// - public CatDogTest() - { - this.CatDogInteger = 0; - - } - - - /// - /// Gets or Sets CatId - /// - [DataMember(Name="cat_id", EmitDefaultValue=false)] - public long? CatId { get; set; } - - - /// - /// Gets or Sets DogId - /// - [DataMember(Name="dog_id", EmitDefaultValue=false)] - public long? DogId { get; set; } - - - /// - /// integer property for testing allOf - /// - /// integer property for testing allOf - [DataMember(Name="CatDogInteger", EmitDefaultValue=false)] - public int? CatDogInteger { get; set; } - - - /// - /// Gets or Sets DogName - /// - [DataMember(Name="dog_name", EmitDefaultValue=false)] - public string DogName { get; set; } - - - /// - /// Gets or Sets CatName - /// - [DataMember(Name="cat_name", EmitDefaultValue=false)] - public string CatName { get; set; } - - - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class CatDogTest {\n"); - sb.Append(" CatId: ").Append(CatId).Append("\n"); - sb.Append(" DogId: ").Append(DogId).Append("\n"); - sb.Append(" CatDogInteger: ").Append(CatDogInteger).Append("\n"); - sb.Append(" DogName: ").Append(DogName).Append("\n"); - sb.Append(" CatName: ").Append(CatName).Append("\n"); - - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public new string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as CatDogTest); - } - - /// - /// Returns true if CatDogTest instances are equal - /// - /// Instance of CatDogTest to be compared - /// Boolean - public bool Equals(CatDogTest other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this.CatId == other.CatId || - this.CatId != null && - this.CatId.Equals(other.CatId) - ) && - ( - this.DogId == other.DogId || - this.DogId != null && - this.DogId.Equals(other.DogId) - ) && - ( - this.CatDogInteger == other.CatDogInteger || - this.CatDogInteger != null && - this.CatDogInteger.Equals(other.CatDogInteger) - ) && - ( - this.DogName == other.DogName || - this.DogName != null && - this.DogName.Equals(other.DogName) - ) && - ( - this.CatName == other.CatName || - this.CatName != null && - this.CatName.Equals(other.CatName) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - - if (this.CatId != null) - hash = hash * 57 + this.CatId.GetHashCode(); - - if (this.DogId != null) - hash = hash * 57 + this.DogId.GetHashCode(); - - if (this.CatDogInteger != null) - hash = hash * 57 + this.CatDogInteger.GetHashCode(); - - if (this.DogName != null) - hash = hash * 57 + this.DogName.GetHashCode(); - - if (this.CatName != null) - hash = hash * 57 + this.CatName.GetHashCode(); - - return hash; - } - } - - } -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumClass.cs deleted file mode 100644 index 1fb5f0b6626..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumClass.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace IO.Swagger.Model -{ - /// - /// Gets or Sets EnumClass - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumClass - { - - /// - /// Enum Abc for "_abc" - /// - [EnumMember(Value = "_abc")] - Abc, - - /// - /// Enum efg for "-efg" - /// - [EnumMember(Value = "-efg")] - efg, - - /// - /// Enum xyz for "(xyz)" - /// - [EnumMember(Value = "(xyz)")] - xyz - } - -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumTest.cs deleted file mode 100644 index f8bebd6b2d7..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/EnumTest.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace IO.Swagger.Model -{ - /// - /// EnumTest - /// - [DataContract] - public partial class EnumTest : IEquatable - { - /// - /// Gets or Sets EnumString - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumStringEnum - { - - /// - /// Enum Upper for "UPPER" - /// - [EnumMember(Value = "UPPER")] - Upper, - - /// - /// Enum Lower for "lower" - /// - [EnumMember(Value = "lower")] - Lower - } - - /// - /// Gets or Sets EnumInteger - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumIntegerEnum - { - - /// - /// Enum NUMBER_1 for 1 - /// - [EnumMember(Value = "1")] - NUMBER_1 = 1, - - /// - /// Enum NUMBER_MINUS_1 for -1 - /// - [EnumMember(Value = "-1")] - NUMBER_MINUS_1 = -1 - } - - /// - /// Gets or Sets EnumNumber - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumNumberEnum - { - - /// - /// Enum NUMBER_1_DOT_1 for 1.1 - /// - [EnumMember(Value = "1.1")] - NUMBER_1_DOT_1, - - /// - /// Enum NUMBER_MINUS_1_DOT_2 for -1.2 - /// - [EnumMember(Value = "-1.2")] - NUMBER_MINUS_1_DOT_2 - } - - /// - /// Gets or Sets EnumString - /// - [DataMember(Name="enum_string", EmitDefaultValue=false)] - public EnumStringEnum? EnumString { get; set; } - /// - /// Gets or Sets EnumInteger - /// - [DataMember(Name="enum_integer", EmitDefaultValue=false)] - public EnumIntegerEnum? EnumInteger { get; set; } - /// - /// Gets or Sets EnumNumber - /// - [DataMember(Name="enum_number", EmitDefaultValue=false)] - public EnumNumberEnum? EnumNumber { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// EnumString. - /// EnumInteger. - /// EnumNumber. - public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) - { - - - this.EnumString = EnumString; - - this.EnumInteger = EnumInteger; - - this.EnumNumber = EnumNumber; - - } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class EnumTest {\n"); - sb.Append(" EnumString: ").Append(EnumString).Append("\n"); -sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); -sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as EnumTest); - } - - /// - /// Returns true if EnumTest instances are equal - /// - /// Instance of EnumTest to be compared - /// Boolean - public bool Equals(EnumTest other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this.EnumString == other.EnumString || - this.EnumString != null && - this.EnumString.Equals(other.EnumString) - ) && - ( - this.EnumInteger == other.EnumInteger || - this.EnumInteger != null && - this.EnumInteger.Equals(other.EnumInteger) - ) && - ( - this.EnumNumber == other.EnumNumber || - this.EnumNumber != null && - this.EnumNumber.Equals(other.EnumNumber) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - if (this.EnumString != null) - hash = hash * 59 + this.EnumString.GetHashCode(); - if (this.EnumInteger != null) - hash = hash * 59 + this.EnumInteger.GetHashCode(); - if (this.EnumNumber != null) - hash = hash * 59 + this.EnumNumber.GetHashCode(); - return hash; - } - } - } - -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/TagCategoryTest.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/TagCategoryTest.cs deleted file mode 100644 index 2cf870ffd77..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/TagCategoryTest.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.Serialization; -using Newtonsoft.Json; - -namespace IO.Swagger.Model -{ - - /// - /// - /// - [DataContract] - public class TagCategoryTest : Category, IEquatable - { - /// - /// Initializes a new instance of the class. - /// - public TagCategoryTest() - { - this.TagCategoryInteger = 0; - - } - - - /// - /// Gets or Sets Id - /// - [DataMember(Name="id", EmitDefaultValue=false)] - public long? Id { get; set; } - - - /// - /// integer property for testing allOf - /// - /// integer property for testing allOf - [DataMember(Name="TagCategoryInteger", EmitDefaultValue=false)] - public int? TagCategoryInteger { get; set; } - - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class TagCategoryTest {\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" TagCategoryInteger: ").Append(TagCategoryInteger).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public new string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as TagCategoryTest); - } - - /// - /// Returns true if TagCategoryTest instances are equal - /// - /// Instance of TagCategoryTest to be compared - /// Boolean - public bool Equals(TagCategoryTest other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this.Id == other.Id || - this.Id != null && - this.Id.Equals(other.Id) - ) && - ( - this.TagCategoryInteger == other.TagCategoryInteger || - this.TagCategoryInteger != null && - this.TagCategoryInteger.Equals(other.TagCategoryInteger) - ) && - ( - this.Name == other.Name || - this.Name != null && - this.Name.Equals(other.Name) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - - if (this.Id != null) - hash = hash * 57 + this.Id.GetHashCode(); - - if (this.TagCategoryInteger != null) - hash = hash * 57 + this.TagCategoryInteger.GetHashCode(); - - if (this.Name != null) - hash = hash * 57 + this.Name.GetHashCode(); - - return hash; - } - } - - } -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj deleted file mode 100644 index c7be212db66..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ /dev/null @@ -1,71 +0,0 @@ - - - - Debug - AnyCPU - {1011E844-3414-4D65-BF1F-7C8CE0167174} - Library - SwaggerClientTest - SwaggerClientTest - v4.5 - - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - false - - - full - true - bin\Release - prompt - 4 - false - - - - - packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - - - packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - - - - - packages\NUnit.2.6.4\lib\nunit.framework.dll - - - - - - - - - - - - - - - - - - - - - - - - - - {0862164F-97E9-4226-B458-E09905B21F2F} - IO.Swagger - - - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln deleted file mode 100644 index 5274859c30a..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln +++ /dev/null @@ -1,23 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwaggerClientTest", "SwaggerClientTest.csproj", "{1011E844-3414-4D65-BF1F-7C8CE0167174}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "..\SwaggerClient\src\IO.Swagger\IO.Swagger.csproj", "{0862164F-97E9-4226-B458-E09905B21F2F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0862164F-97E9-4226-B458-E09905B21F2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0862164F-97E9-4226-B458-E09905B21F2F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0862164F-97E9-4226-B458-E09905B21F2F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0862164F-97E9-4226-B458-E09905B21F2F}.Release|Any CPU.Build.0 = Release|Any CPU - {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1011E844-3414-4D65-BF1F-7C8CE0167174}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1011E844-3414-4D65-BF1F-7C8CE0167174}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs deleted file mode 100644 index b87503528b6..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestEnum.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestEnum.cs deleted file mode 100644 index 0ca6bb6c2a6..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestEnum.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NUnit.Framework; -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using IO.Swagger.Api; -using IO.Swagger.Model; -using IO.Swagger.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace SwaggerClientTest.TestEnum -{ - [TestFixture ()] - public class TestEnum - { - public TestEnum () - { - } - - /// - /// Test EnumClass - /// - [Test ()] - public void TestEnumClass () - { - // test serialization for string - Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumClass.Abc), "\"_abc\""); - - // test serialization for number - Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1), "\"-1\""); - - // test cast to int - Assert.AreEqual ((int)EnumTest.EnumIntegerEnum.NUMBER_MINUS_1, -1); - - } - } -} - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestOrder.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestOrder.cs deleted file mode 100644 index 59411416a76..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestOrder.cs +++ /dev/null @@ -1,112 +0,0 @@ -using NUnit.Framework; -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using IO.Swagger.Api; -using IO.Swagger.Model; -using IO.Swagger.Client; -using System.Reflection; -using Newtonsoft.Json; - - -namespace SwaggerClientTest.TestOrder -{ - [TestFixture ()] - public class TestOrder - { - public TestOrder () - { - - } - - /// - /// Test creating a new instance of Order - /// - [Test ()] - public void TestNewOrder() - { - Order o = new Order (); - - Assert.IsNull (o.Id); - - } - - /// - /// Test deserialization of JSON to Order and its readonly property - /// - [Test ()] - public void TesOrderDeserialization() - { - string json = @"{ -'id': 1982, -'petId': 1020, -'quantity': 1, -'status': 'placed', -'complete': true, -}"; - var o = JsonConvert.DeserializeObject(json); - Assert.AreEqual (1982, o.Id); - Assert.AreEqual (1020, o.PetId); - Assert.AreEqual (1, o.Quantity); - Assert.AreEqual (Order.StatusEnum.Placed, o.Status); - Assert.AreEqual (true, o.Complete); - - } - - /// - /// Test GetInvetory - /// - [Test ()] - public void TestGetInventory () - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); - - StoreApi storeApi = new StoreApi (c1); - Dictionary response = storeApi.GetInventory (); - - foreach(KeyValuePair entry in response) - { - Assert.IsInstanceOf (typeof(int?), entry.Value); - } - - } - - /* - * Skip the following test as the fake endpiont has been removed from the swagger spec - * We'll uncomment below after we update the Petstore server - /// - /// Test TestGetInventoryInObject - /// - [Test ()] - public void TestGetInventoryInObject() - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); - - StoreApi storeApi = new StoreApi (c1); - Newtonsoft.Json.Linq.JObject response = (Newtonsoft.Json.Linq.JObject)storeApi.GetInventoryInObject (); - - // should be a Newtonsoft.Json.Linq.JObject since type is object - Assert.IsInstanceOf (typeof(Newtonsoft.Json.Linq.JObject), response); - - foreach(KeyValuePair entry in response.ToObject>()) - { - Assert.IsInstanceOf (typeof(int?), Int32.Parse(entry.Value)); - } - } - */ - - /// - /// Test Enum - /// - [Test ()] - public void TestEnum () - { - Assert.AreEqual (Order.StatusEnum.Approved.ToString(), "Approved"); - - } - } -} - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs deleted file mode 100644 index 25d2255542a..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ /dev/null @@ -1,386 +0,0 @@ -using NUnit.Framework; -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using IO.Swagger.Api; -using IO.Swagger.Model; -using IO.Swagger.Client; -using System.Reflection; - -namespace SwaggerClientTest.TestPet -{ - [TestFixture ()] - public class TestPet - { - public long petId = 11088; - - /// - /// Create a Pet object - /// - private Pet createPet() - { - // create pet - Pet p = new Pet(Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test" }); - p.Id = petId; - //p.Name = "Csharp test"; - p.Status = Pet.StatusEnum.Available; - // create Category object - Category category = new Category(); - category.Id = 56; - category.Name = "sample category name2"; - List photoUrls = new List(new String[] {"sample photoUrls"}); - // create Tag object - Tag tag = new Tag(); - tag.Id = petId; - tag.Name = "csharp sample tag name1"; - List tags = new List(new Tag[] {tag}); - p.Tags = tags; - p.Category = category; - p.PhotoUrls = photoUrls; - - return p; - } - - /// - /// Convert string to byte array - /// - private byte[] GetBytes(string str) - { - byte[] bytes = new byte[str.Length * sizeof(char)]; - System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); - return bytes; - } - - [SetUp] public void Init() - { - // create pet - Pet p = createPet(); - - // add pet before testing - PetApi petApi = new PetApi("http://petstore.swagger.io/v2/"); - petApi.AddPet (p); - - } - - [TearDown] public void Cleanup() - { - // remove the pet after testing - PetApi petApi = new PetApi (); - petApi.DeletePet(petId, "test key"); - } - - /// - /// Test GetPetByIdAsync - /// - [Test ()] - public void TestGetPetByIdAsync () - { - PetApi petApi = new PetApi (); - var task = petApi.GetPetByIdAsync (petId); - Pet response = task.Result; - Assert.IsInstanceOf (response, "Response is a Pet"); - - Assert.AreEqual ("Csharp test", response.Name); - Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); - Assert.AreEqual (petId, response.Tags [0].Id); - Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); - Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); - Assert.AreEqual (56, response.Category.Id); - Assert.AreEqual ("sample category name2", response.Category.Name); - - } - - /// - /// Test GetPetByIdAsyncWithHttpInfo - /// - [Test ()] - public void TestGetPetByIdAsyncWithHttpInfo () - { - PetApi petApi = new PetApi (); - var task = petApi.GetPetByIdAsyncWithHttpInfo (petId); - - Assert.AreEqual (200, task.Result.StatusCode); - Assert.IsTrue (task.Result.Headers.ContainsKey("Content-Type")); - Assert.AreEqual (task.Result.Headers["Content-Type"], "application/json"); - - Pet response = task.Result.Data; - Assert.IsInstanceOf (response, "Response is a Pet"); - - Assert.AreEqual ("Csharp test", response.Name); - Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); - Assert.AreEqual (petId, response.Tags [0].Id); - Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); - Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); - Assert.AreEqual (56, response.Category.Id); - Assert.AreEqual ("sample category name2", response.Category.Name); - - } - - /// - /// Test GetPetById - /// - [Test ()] - public void TestGetPetById () - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000, userAgent: "TEST_USER_AGENT"); - - PetApi petApi = new PetApi (c1); - Pet response = petApi.GetPetById (petId); - Assert.IsInstanceOf (response, "Response is a Pet"); - - Assert.AreEqual ("Csharp test", response.Name); - Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); - Assert.AreEqual (petId, response.Tags [0].Id); - Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); - Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); - Assert.AreEqual (56, response.Category.Id); - Assert.AreEqual ("sample category name2", response.Category.Name); - - } - - /* comment out the test case as the method is not defined in original petstore spec - * we will re-enable this after updating the petstore server - * - /// - /// Test GetPetByIdInObject - /// - [Test ()] - public void TestGetPetByIdInObject () - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); - - PetApi petApi = new PetApi (c1); - InlineResponse200 response = petApi.GetPetByIdInObject (petId); - Assert.IsInstanceOf (response, "Response is a Pet"); - - Assert.AreEqual ("Csharp test", response.Name); - Assert.AreEqual (InlineResponse200.StatusEnum.Available, response.Status); - - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); - Assert.AreEqual (petId, response.Tags [0].Id); - Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); - Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - - Assert.IsInstanceOf (response.Category, "Response.Category is a Newtonsoft.Json.Linq.JObject"); - - Newtonsoft.Json.Linq.JObject category = (Newtonsoft.Json.Linq.JObject)response.Category; - Assert.AreEqual (56, (int)category ["id"]); - Assert.AreEqual ("sample category name2", (string) category["name"]); - - }*/ - - /* comment out the test case as the method is not defined in original petstore spec - * we will re-enable this after updating the petstore server - * - /// - /// Test GetPetByIdWithByteArray - /// - [Test ()] - public void TestGetPetByIdWithByteArray () - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); - - PetApi petApi = new PetApi (c1); - byte[] response = petApi.PetPetIdtestingByteArraytrueGet (petId); - Assert.IsInstanceOf (response, "Response is byte array"); - }*/ - - /* comment out the test case as the method is not defined in original petstore spec - * we will re-enable this after updating the petstore server - * - /// - /// Test AddPetUsingByteArray - /// - [Test ()] - public void TestAddPetUsingByteArray () - { - // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); - - PetApi petApi = new PetApi (c1); - Pet p = createPet (); - byte[] petByteArray = GetBytes ((string)petApi.Configuration.ApiClient.Serialize (p)); - petApi.AddPetUsingByteArray (petByteArray); - }*/ - - /// - /// Test UpdatePetWithForm - /// - [Test ()] - public void TestUpdatePetWithForm () - { - PetApi petApi = new PetApi (); - petApi.UpdatePetWithForm (petId, "new form name", "pending"); - - Pet response = petApi.GetPetById (petId); - Assert.IsInstanceOf (response, "Response is a Pet"); - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); - - Assert.AreEqual ("new form name", response.Name); - Assert.AreEqual (Pet.StatusEnum.Pending, response.Status); - - Assert.AreEqual (petId, response.Tags [0].Id); - Assert.AreEqual (56, response.Category.Id); - - // test optional parameter - petApi.UpdatePetWithForm (petId, "new form name2"); - Pet response2 = petApi.GetPetById (petId); - Assert.AreEqual ("new form name2", response2.Name); - } - - /// - /// Test UploadFile - /// - [Test ()] - public void TestUploadFile () - { - Assembly _assembly = Assembly.GetExecutingAssembly(); - Stream _imageStream = _assembly.GetManifestResourceStream("SwaggerClientTest.swagger-logo.png"); - PetApi petApi = new PetApi (); - // test file upload with form parameters - petApi.UploadFile(petId, "new form name", _imageStream); - - // test file upload without any form parameters - // using optional parameter syntax introduced at .net 4.0 - petApi.UploadFile(petId: petId, file: _imageStream); - - } - - /// - /// Test FindPetByStatus - /// - [Test ()] - public void TestFindPetByTags () - { - PetApi petApi = new PetApi (); - List tagsList = new List(new String[] {"available"}); - - List listPet = petApi.FindPetsByTags (tagsList); - foreach (Pet pet in listPet) // Loop through List with foreach. - { - Assert.IsInstanceOf (pet, "Response is a Pet"); - Assert.AreEqual ("csharp sample tag name1", pet.Tags[0]); - } - - } - - /// - /// Test Equal - /// - [Test ()] - public void TestEqual() - { - // create pet - Pet p1 = new Pet(Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test"} ); - p1.Id = petId; - //p1.Name = "Csharp test"; - p1.Status = Pet.StatusEnum.Available; - // create Category object - Category category1 = new Category(); - category1.Id = 56; - category1.Name = "sample category name2"; - List photoUrls1 = new List(new String[] {"sample photoUrls"}); - // create Tag object - Tag tag1 = new Tag(); - tag1.Id = petId; - tag1.Name = "csharp sample tag name1"; - List tags1 = new List(new Tag[] {tag1}); - p1.Tags = tags1; - p1.Category = category1; - p1.PhotoUrls = photoUrls1; - - // create pet 2 - Pet p2 = new Pet(Name: "Csharp test", PhotoUrls: new List { "http://petstore.com/csharp_test"} ); - p2.Id = petId; - p2.Name = "Csharp test"; - p2.Status = Pet.StatusEnum.Available; - // create Category object - Category category2 = new Category(); - category2.Id = 56; - category2.Name = "sample category name2"; - List photoUrls2 = new List(new String[] {"sample photoUrls"}); - // create Tag object - Tag tag2 = new Tag(); - tag2.Id = petId; - tag2.Name = "csharp sample tag name1"; - List tags2 = new List(new Tag[] {tag2}); - p2.Tags = tags2; - p2.Category = category2; - p2.PhotoUrls = photoUrls2; - - // p1 and p2 should be equal (both object and attribute level) - Assert.IsTrue (category1.Equals (category2)); - Assert.IsTrue (tags1.SequenceEqual (tags2)); - Assert.IsTrue (p1.PhotoUrls.SequenceEqual(p2.PhotoUrls)); - - Assert.IsTrue (p1.Equals (p2)); - - // update attribute to that p1 and p2 are not equal - category2.Name = "new category name"; - Assert.IsFalse(category1.Equals (category2)); - - tags2 = new List (); - Assert.IsFalse (tags1.SequenceEqual (tags2)); - - // photoUrls has not changed so it should be equal - Assert.IsTrue (p1.PhotoUrls.SequenceEqual(p2.PhotoUrls)); - - Assert.IsFalse (p1.Equals (p2)); - - } - - /// - /// Test status code - /// - [Test ()] - public void TestStatusCodeAndHeader () - { - PetApi petApi = new PetApi (); - var response = petApi.GetPetByIdWithHttpInfo (petId); - Assert.AreEqual (response.StatusCode, 200); - Assert.IsTrue (response.Headers.ContainsKey("Content-Type")); - Assert.AreEqual (response.Headers["Content-Type"], "application/json"); - } - - /// - /// Test default header (should be deprecated - /// - [Test ()] - public void TestDefaultHeader () - { - PetApi petApi = new PetApi (); - // commented out the warning test below as it's confirmed the warning is working as expected - // there should be a warning for using AddDefaultHeader (deprecated) below - //petApi.AddDefaultHeader ("header_key", "header_value"); - // the following should be used instead as suggested in the doc - petApi.Configuration.AddDefaultHeader ("header_key2", "header_value2"); - - } - } -} - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/mono-nunit.sh b/samples/client/petstore/csharp/SwaggerClientTest/mono-nunit.sh deleted file mode 100755 index c14e76dad05..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/mono-nunit.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -wget -nc https://nuget.org/nuget.exe; -mozroots --import --sync - -# remove bin/Debug/SwaggerClientTest.dll -rm bin/Debug/SwaggerClientTest.dll 2> /dev/null - -# install NUnit runners via NuGet -mono nuget.exe install NUnit.Runners -Version 2.6.4 -OutputDirectory testrunner - -# build the solution and run the unit test -xbuild SwaggerClientTest.sln && \ -mono ./testrunner/NUnit.Runners.2.6.4/tools/nunit-console.exe bin/Debug/SwaggerClientTest.dll - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt deleted file mode 100644 index fe5b5e6a930..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ /dev/null @@ -1,11 +0,0 @@ -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll -/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages.config b/samples/client/petstore/csharp/SwaggerClientTest/packages.config deleted file mode 100644 index 0a536655794..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/NUnit.2.6.4.nupkg b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/NUnit.2.6.4.nupkg deleted file mode 100644 index 379b15bf5cd..00000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/NUnit.2.6.4.nupkg and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.dll b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.dll deleted file mode 100644 index ed6550bb055..00000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.xml b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.xml deleted file mode 100644 index 532d8286707..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/lib/nunit.framework.xml +++ /dev/null @@ -1,10984 +0,0 @@ - - - - nunit.framework - - - - - The different targets a test action attribute can be applied to - - - - - Default target, which is determined by where the action attribute is attached - - - - - Target a individual test case - - - - - Target a suite of test cases - - - - - Delegate used by tests that execute code and - capture any thrown exception. - - - - - The Assert class contains a collection of static methods that - implement the most common assertions used in NUnit. - - - - - We don't actually want any instances of this object, but some people - like to inherit from it to add other static methods. Hence, the - protected constructor disallows any instances of this object. - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - Throws a with the message and arguments - that are passed in. This allows a test to be cut short, with a result - of success returned to NUnit. - - The message to initialize the with. - Arguments to be used in formatting the message - - - - Throws a with the message and arguments - that are passed in. This allows a test to be cut short, with a result - of success returned to NUnit. - - The message to initialize the with. - - - - Throws a with the message and arguments - that are passed in. This allows a test to be cut short, with a result - of success returned to NUnit. - - - - - Throws an with the message and arguments - that are passed in. This is used by the other Assert functions. - - The message to initialize the with. - Arguments to be used in formatting the message - - - - Throws an with the message that is - passed in. This is used by the other Assert functions. - - The message to initialize the with. - - - - Throws an . - This is used by the other Assert functions. - - - - - Throws an with the message and arguments - that are passed in. This causes the test to be reported as ignored. - - The message to initialize the with. - Arguments to be used in formatting the message - - - - Throws an with the message that is - passed in. This causes the test to be reported as ignored. - - The message to initialize the with. - - - - Throws an . - This causes the test to be reported as ignored. - - - - - Throws an with the message and arguments - that are passed in. This causes the test to be reported as inconclusive. - - The message to initialize the with. - Arguments to be used in formatting the message - - - - Throws an with the message that is - passed in. This causes the test to be reported as inconclusive. - - The message to initialize the with. - - - - Throws an . - This causes the test to be reported as Inconclusive. - - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint expression to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display if the condition is false - Arguments to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display if the condition is false - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - An ActualValueDelegate returning the value to be tested - A Constraint expression to be applied - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - An ActualValueDelegate returning the value to be tested - A Constraint expression to be applied - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - An ActualValueDelegate returning the value to be tested - A Constraint expression to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that the code represented by a delegate throws an exception - that satisfies the constraint provided. - - A TestDelegate to be executed - A ThrowsConstraint used in the test - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - Used as a synonym for That in rare cases where a private setter - causes a Visual Basic compilation error. - - The actual value to test - A Constraint to be applied - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - Used as a synonym for That in rare cases where a private setter - causes a Visual Basic compilation error. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - Used as a synonym for That in rare cases where a private setter - causes a Visual Basic compilation error. - - - This method is provided for use by VB developers needing to test - the value of properties with private setters. - - The actual value to test - A Constraint expression to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws a particular exception when called. - - A constraint to be satisfied by the exception - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws a particular exception when called. - - A constraint to be satisfied by the exception - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws a particular exception when called. - - A constraint to be satisfied by the exception - A TestDelegate - - - - Verifies that a delegate throws a particular exception when called. - - The exception Type expected - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws a particular exception when called. - - The exception Type expected - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws a particular exception when called. - - The exception Type expected - A TestDelegate - - - - Verifies that a delegate throws a particular exception when called. - - Type of the expected exception - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws a particular exception when called. - - Type of the expected exception - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws a particular exception when called. - - Type of the expected exception - A TestDelegate - - - - Verifies that a delegate throws an exception when called - and returns it. - - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws an exception when called - and returns it. - - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws an exception when called - and returns it. - - A TestDelegate - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate throws an exception of a certain Type - or one derived from it when called and returns it. - - The expected Exception Type - A TestDelegate - - - - Verifies that a delegate does not throw an exception - - A TestDelegate - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that a delegate does not throw an exception. - - A TestDelegate - The message that will be displayed on failure - - - - Verifies that a delegate does not throw an exception. - - A TestDelegate - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display in case of failure - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display in case of failure - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - The message to display in case of failure - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - The message to display in case of failure - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - - - - Verifies that the object that is passed in is not equal to null - If the object is null then an - is thrown. - - The object that is to be tested - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - The message to display in case of failure - - - - Verifies that the object that is passed in is equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - - - - Verifies that two ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two unsigned ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two unsigned ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two unsigned ints are equal. If they are not, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two unsigned longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two unsigned longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two unsigned longs are equal. If they are not, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two decimals are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two decimals are equal. If they are not, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two decimals are equal. If they are not, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message to display in case of failure - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message to display in case of failure - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equal then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are not equal an is thrown. - - The value that is expected - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are not equal an is thrown. - - The value that is expected - The actual value - The message to display in case of failure - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are not equal an is thrown. - - The value that is expected - The actual value - - - - Verifies that two ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two unsigned ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two unsigned ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two unsigned ints are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two unsigned longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two unsigned longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two unsigned longs are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two decimals are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two decimals are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two decimals are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two floats are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two floats are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two floats are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two doubles are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two doubles are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - The message to display in case of failure - - - - Verifies that two doubles are not equal. If they are equal, then an - is thrown. - - The expected value - The actual value - - - - Verifies that two objects are not equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are equal an is thrown. - - The value that is expected - The actual value - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that two objects are not equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are equal an is thrown. - - The value that is expected - The actual value - The message to display in case of failure - - - - Verifies that two objects are not equal. Two objects are considered - equal if both are null, or if both have the same value. NUnit - has special semantics for some object types. - If they are equal an is thrown. - - The value that is expected - The actual value - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The expected object - The actual object - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The expected object - The actual object - The message to display in case of failure - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The expected object - The actual object - - - - Asserts that two objects do not refer to the same object. If they - are the same an is thrown. - - The expected object - The actual object - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that two objects do not refer to the same object. If they - are the same an is thrown. - - The expected object - The actual object - The message to display in case of failure - - - - Asserts that two objects do not refer to the same object. If they - are the same an is thrown. - - The expected object - The actual object - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - The message to display in case of failure - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - The message to display in case of failure - - - - Verifies that the double that is passed in is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - - - - Assert that a string is empty - that is equal to string.Empty - - The string to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that a string is empty - that is equal to string.Empty - - The string to be tested - The message to display in case of failure - - - - Assert that a string is empty - that is equal to string.Empty - - The string to be tested - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to display in case of failure - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - - - - Assert that a string is not empty - that is not equal to string.Empty - - The string to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that a string is not empty - that is not equal to string.Empty - - The string to be tested - The message to display in case of failure - - - - Assert that a string is not empty - that is not equal to string.Empty - - The string to be tested - - - - Assert that an array, list or other collection is not empty - - An array, list or other collection implementing ICollection - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that an array, list or other collection is not empty - - An array, list or other collection implementing ICollection - The message to display in case of failure - - - - Assert that an array, list or other collection is not empty - - An array, list or other collection implementing ICollection - - - - Assert that a string is either null or equal to string.Empty - - The string to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that a string is either null or equal to string.Empty - - The string to be tested - The message to display in case of failure - - - - Assert that a string is either null or equal to string.Empty - - The string to be tested - - - - Assert that a string is not null or empty - - The string to be tested - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Assert that a string is not null or empty - - The string to be tested - The message to display in case of failure - - - - Assert that a string is not null or empty - - The string to be tested - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - The message to display in case of failure - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than the second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message to display in case of failure - - - - Verifies that the first value is greater than or equal tothe second - value. If it is not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message to display in case of failure - - - - Verifies that the first value is less than or equal to the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Asserts that an object is contained in a list. - - The expected object - The list to be examined - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is contained in a list. - - The expected object - The list to be examined - The message to display in case of failure - - - - Asserts that an object is contained in a list. - - The expected object - The list to be examined - - - - Helper for Assert.AreEqual(double expected, double actual, ...) - allowing code generation to work consistently. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Gets the number of assertions executed so far and - resets the counter to zero. - - - - - AssertionHelper is an optional base class for user tests, - allowing the use of shorter names for constraints and - asserts and avoiding conflict with the definition of - , from which it inherits much of its - behavior, in certain mock object frameworks. - - - - - Helper class with properties and methods that supply - a number of constraints used in Asserts. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding only if a specified number of them succeed. - - - - - Returns a new PropertyConstraintExpression, which will either - test for the existence of the named property on the object - being tested or apply any following constraint to that property. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns a constraint that tests two items for equality - - - - - Returns a constraint that tests that two references are the same object - - - - - Returns a constraint that tests whether the - actual value is greater than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a collection containing the same elements as the - collection supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a subset of the collection supplied as an argument. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a new ContainsConstraint. This constraint - will, in turn, make use of the appropriate second-level - constraint, depending on the type of the actual argument. - This overload is only used if the item sought is a string, - since any other type implies that we are looking for a - collection member. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the regular expression supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the regular expression supplied as an argument. - - - - - Returns a constraint that fails if the actual - value matches the pattern supplied as an argument. - - - - - Returns a constraint that tests whether the path provided - is the same as an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is the same path or under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is the same path or under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the actual value falls - within a specified range. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them succeed. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if at least one of them succeeds. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them fail. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Length property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Count property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Message property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the InnerException property of the object being tested. - - - - - Returns a constraint that tests for null - - - - - Returns a constraint that tests for True - - - - - Returns a constraint that tests for False - - - - - Returns a constraint that tests for a positive value - - - - - Returns a constraint that tests for a negative value - - - - - Returns a constraint that tests for NaN - - - - - Returns a constraint that tests for empty - - - - - Returns a constraint that tests whether a collection - contains all unique items. - - - - - Returns a constraint that tests whether an object graph is serializable in binary format. - - - - - Returns a constraint that tests whether an object graph is serializable in xml format. - - - - - Returns a constraint that tests whether a collection is ordered - - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. Works - identically to Assert.That. - - The actual value to test - A Constraint to be applied - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. Works - identically to Assert.That. - - The actual value to test - A Constraint to be applied - The message to be displayed in case of failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. Works - identically to Assert.That. - - The actual value to test - A Constraint to be applied - The message to be displayed in case of failure - Arguments to use in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . Works Identically to - . - - The evaluated condition - The message to display if the condition is false - Arguments to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . Works Identically to - . - - The evaluated condition - The message to display if the condition is false - - - - Asserts that a condition is true. If the condition is false the method throws - an . Works Identically to . - - The evaluated condition - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - A Constraint expression to be applied - An ActualValueDelegate returning the value to be tested - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - A Constraint expression to be applied - An ActualValueDelegate returning the value to be tested - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - An ActualValueDelegate returning the value to be tested - A Constraint expression to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an assertion exception on failure. - - The actual value to test - A Constraint to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that the code represented by a delegate throws an exception - that satisfies the constraint provided. - - A TestDelegate to be executed - A ThrowsConstraint used in the test - - - - Returns a ListMapper based on a collection. - - The original collection - - - - - Provides static methods to express the assumptions - that must be met for a test to give a meaningful - result. If an assumption is not met, the test - should produce an inconclusive result. - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display if the condition is false - Arguments to be used in formatting the message - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - The message to display if the condition is false - - - - Asserts that a condition is true. If the condition is false the - method throws an . - - The evaluated condition - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - An ActualValueDelegate returning the value to be tested - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - An ActualValueDelegate returning the value to be tested - The message that will be displayed on failure - - - - Apply a constraint to an actual value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - An ActualValueDelegate returning the value to be tested - A Constraint expression to be applied - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - The message that will be displayed on failure - - - - Apply a constraint to a referenced value, succeeding if the constraint - is satisfied and throwing an InconclusiveException on failure. - - A Constraint expression to be applied - The actual value to test - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that the code represented by a delegate throws an exception - that satisfies the constraint provided. - - A TestDelegate to be executed - A ThrowsConstraint used in the test - - - - Waits for pending asynchronous operations to complete, if appropriate, - and returns a proper result of the invocation by unwrapping task results - - The raw result of the method invocation - The unwrapped result, if necessary - - - - A set of Assert methods operationg on one or more collections - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - IEnumerable containing objects to be considered - System.Type that all objects in collection must be instances of - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - IEnumerable containing objects to be considered - System.Type that all objects in collection must be instances of - The message that will be displayed on failure - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - IEnumerable containing objects to be considered - System.Type that all objects in collection must be instances of - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that all items contained in collection are not equal to null. - - IEnumerable containing objects to be considered - - - - Asserts that all items contained in collection are not equal to null. - - IEnumerable containing objects to be considered - The message that will be displayed on failure - - - - Asserts that all items contained in collection are not equal to null. - - IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - IEnumerable of objects to be considered - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - IEnumerable of objects to be considered - The message that will be displayed on failure - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - The message that will be displayed on failure - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are exactly equal. The collections must have the same count, - and contain the exact same objects in the same order. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not exactly equal. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - - - - Asserts that expected and actual are not exactly equal. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - The message that will be displayed on failure - - - - Asserts that expected and actual are not exactly equal. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The IComparer to use in comparing objects from each IEnumerable - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not equivalent. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - - - - Asserts that expected and actual are not equivalent. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are not equivalent. - - The first IEnumerable of objects to be considered - The second IEnumerable of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that collection contains actual as an item. - - IEnumerable of objects to be considered - Object to be found within collection - - - - Asserts that collection contains actual as an item. - - IEnumerable of objects to be considered - Object to be found within collection - The message that will be displayed on failure - - - - Asserts that collection contains actual as an item. - - IEnumerable of objects to be considered - Object to be found within collection - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that collection does not contain actual as an item. - - IEnumerable of objects to be considered - Object that cannot exist within collection - - - - Asserts that collection does not contain actual as an item. - - IEnumerable of objects to be considered - Object that cannot exist within collection - The message that will be displayed on failure - - - - Asserts that collection does not contain actual as an item. - - IEnumerable of objects to be considered - Object that cannot exist within collection - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that the superset does not contain the subset - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - - - - Asserts that the superset does not contain the subset - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - The message that will be displayed on failure - - - - Asserts that the superset does not contain the subset - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that the superset contains the subset. - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - - - - Asserts that the superset contains the subset. - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - The message that will be displayed on failure - - - - Asserts that the superset contains the subset. - - The IEnumerable subset to be considered - The IEnumerable superset to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - - - - Assert that an array,list or other collection is empty - - An array, list or other collection implementing IEnumerable - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - - - - Assert that an array,list or other collection is empty - - An array, list or other collection implementing IEnumerable - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - The message to be displayed on failure - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - A custom comparer to perform the comparisons - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - A custom comparer to perform the comparisons - The message to be displayed on failure - - - - Assert that an array, list or other collection is ordered - - An array, list or other collection implementing IEnumerable - A custom comparer to perform the comparisons - - - - Helper class with properties and methods that supply - a number of constraints used in Asserts. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Summary description for DirectoryAssert - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - We don't actually want any instances of this object, but some people - like to inherit from it to add other static methods. Hence, the - protected constructor disallows any instances of this object. - - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - The message to display if directories are not equal - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - The message to display if directories are not equal - - - - Verifies that two directories are equal. Two directories are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - The message to display if directories are not equal - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory containing the value that is expected - A directory containing the actual value - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - The message to display if directories are equal - Arguments to be used in formatting the message - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - The message to display if directories are equal - - - - Asserts that two directories are not equal. If they are equal - an is thrown. - - A directory path string containing the value that is expected - A directory path string containing the actual value - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - The message to display if directories are not equal - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - The message to display if directories are not equal - - - - Asserts that the directory is empty. If it is not empty - an is thrown. - - A directory to search - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - The message to display if directories are not equal - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - The message to display if directories are not equal - Arguments to be used in formatting the message - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - The message to display if directories are not equal - - - - Asserts that the directory is not empty. If it is empty - an is thrown. - - A directory to search - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - Arguments to be used in formatting the message - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - Arguments to be used in formatting the message - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - - - - Asserts that path contains actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - Arguments to be used in formatting the message - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - Arguments to be used in formatting the message - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - The message to display if directory is not within the path - - - - Asserts that path does not contain actual as a subdirectory or - an is thrown. - - A directory to search - sub-directory asserted to exist under directory - - - - Summary description for FileAssert. - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - We don't actually want any instances of this object, but some people - like to inherit from it to add other static methods. Hence, the - protected constructor disallows any instances of this object. - - - - - Verifies that two Streams are equal. Two Streams are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The expected Stream - The actual Stream - The message to display if Streams are not equal - Arguments to be used in formatting the message - - - - Verifies that two Streams are equal. Two Streams are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The expected Stream - The actual Stream - The message to display if objects are not equal - - - - Verifies that two Streams are equal. Two Streams are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The expected Stream - The actual Stream - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A file containing the value that is expected - A file containing the actual value - The message to display if Streams are not equal - Arguments to be used in formatting the message - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A file containing the value that is expected - A file containing the actual value - The message to display if objects are not equal - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - A file containing the value that is expected - A file containing the actual value - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - The message to display if Streams are not equal - Arguments to be used in formatting the message - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - The message to display if objects are not equal - - - - Verifies that two files are equal. Two files are considered - equal if both are null, or if both have the same value byte for byte. - If they are not equal an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - - - - Asserts that two Streams are not equal. If they are equal - an is thrown. - - The expected Stream - The actual Stream - The message to be displayed when the two Stream are the same. - Arguments to be used in formatting the message - - - - Asserts that two Streams are not equal. If they are equal - an is thrown. - - The expected Stream - The actual Stream - The message to be displayed when the Streams are the same. - - - - Asserts that two Streams are not equal. If they are equal - an is thrown. - - The expected Stream - The actual Stream - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - A file containing the value that is expected - A file containing the actual value - The message to display if Streams are not equal - Arguments to be used in formatting the message - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - A file containing the value that is expected - A file containing the actual value - The message to display if objects are not equal - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - A file containing the value that is expected - A file containing the actual value - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - The message to display if Streams are not equal - Arguments to be used in formatting the message - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - The message to display if objects are not equal - - - - Asserts that two files are not equal. If they are equal - an is thrown. - - The path to a file containing the value that is expected - The path to a file containing the actual value - - - - GlobalSettings is a place for setting default values used - by the framework in performing asserts. - - - - - Default tolerance for floating point equality - - - - - Class used to guard against unexpected argument values - by throwing an appropriate exception. - - - - - Throws an exception if an argument is null - - The value to be tested - The name of the argument - - - - Throws an exception if a string argument is null or empty - - The value to be tested - The name of the argument - - - - Helper class with properties and methods that supply - a number of constraints used in Asserts. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding only if a specified number of them succeed. - - - - - Returns a new PropertyConstraintExpression, which will either - test for the existence of the named property on the object - being tested or apply any following constraint to that property. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them succeed. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if at least one of them succeeds. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them fail. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Length property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Count property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Message property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the InnerException property of the object being tested. - - - - - Interface implemented by a user fixture in order to - validate any expected exceptions. It is only called - for test methods marked with the ExpectedException - attribute. - - - - - Method to handle an expected exception - - The exception to be handled - - - - Helper class with properties and methods that supply - a number of constraints used in Asserts. - - - - - Returns a constraint that tests two items for equality - - - - - Returns a constraint that tests that two references are the same object - - - - - Returns a constraint that tests whether the - actual value is greater than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a collection containing the same elements as the - collection supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a subset of the collection supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the regular expression supplied as an argument. - - - - - Returns a constraint that tests whether the path provided - is the same as an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is the same path or under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the actual value falls - within a specified range. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them succeed. - - - - - Returns a constraint that tests for null - - - - - Returns a constraint that tests for True - - - - - Returns a constraint that tests for False - - - - - Returns a constraint that tests for a positive value - - - - - Returns a constraint that tests for a negative value - - - - - Returns a constraint that tests for NaN - - - - - Returns a constraint that tests for empty - - - - - Returns a constraint that tests whether a collection - contains all unique items. - - - - - Returns a constraint that tests whether an object graph is serializable in binary format. - - - - - Returns a constraint that tests whether an object graph is serializable in xml format. - - - - - Returns a constraint that tests whether a collection is ordered - - - - - The ITestCaseData interface is implemented by a class - that is able to return complete testcases for use by - a parameterized test method. - - NOTE: This interface is used in both the framework - and the core, even though that results in two different - types. However, sharing the source code guarantees that - the various implementations will be compatible and that - the core is able to reflect successfully over the - framework implementations of ITestCaseData. - - - - - Gets the argument list to be provided to the test - - - - - Gets the expected result - - - - - Indicates whether a result has been specified. - This is necessary because the result may be - null, so it's value cannot be checked. - - - - - Gets the expected exception Type - - - - - Gets the FullName of the expected exception - - - - - Gets the name to be used for the test - - - - - Gets the description of the test - - - - - Gets a value indicating whether this is ignored. - - true if ignored; otherwise, false. - - - - Gets a value indicating whether this is explicit. - - true if explicit; otherwise, false. - - - - Gets the ignore reason. - - The ignore reason. - - - - The Iz class is a synonym for Is intended for use in VB, - which regards Is as a keyword. - - - - - The List class is a helper class with properties and methods - that supply a number of constraints used with lists and collections. - - - - - List.Map returns a ListMapper, which can be used to map - the original collection to another collection. - - - - - - - ListMapper is used to transform a collection used as an actual argument - producing another collection to be used in the assertion. - - - - - Construct a ListMapper based on a collection - - The collection to be transformed - - - - Produces a collection containing all the values of a property - - The collection of property values - - - - - Randomizer returns a set of random values in a repeatable - way, to allow re-running of tests if necessary. - - - - - Get a randomizer for a particular member, returning - one that has already been created if it exists. - This ensures that the same values are generated - each time the tests are reloaded. - - - - - Get a randomizer for a particular parameter, returning - one that has already been created if it exists. - This ensures that the same values are generated - each time the tests are reloaded. - - - - - Construct a randomizer using a random seed - - - - - Construct a randomizer using a specified seed - - - - - Return an array of random doubles between 0.0 and 1.0. - - - - - - - Return an array of random doubles with values in a specified range. - - - - - Return an array of random ints with values in a specified range. - - - - - Get a random seed for use in creating a randomizer. - - - - - The SpecialValue enum is used to represent TestCase arguments - that cannot be used as arguments to an Attribute. - - - - - Null represents a null value, which cannot be used as an - argument to an attribute under .NET 1.x - - - - - Basic Asserts on strings. - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - Asserts that a string is found within another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string is found within another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string is found within another string. - - The expected string - The string to be examined - - - - Asserts that a string is not found within another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string is found within another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string is found within another string. - - The expected string - The string to be examined - - - - Asserts that a string starts with another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string starts with another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string starts with another string. - - The expected string - The string to be examined - - - - Asserts that a string does not start with another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string does not start with another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string does not start with another string. - - The expected string - The string to be examined - - - - Asserts that a string ends with another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string ends with another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string ends with another string. - - The expected string - The string to be examined - - - - Asserts that a string does not end with another string. - - The expected string - The string to be examined - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string does not end with another string. - - The expected string - The string to be examined - The message to display in case of failure - - - - Asserts that a string does not end with another string. - - The expected string - The string to be examined - - - - Asserts that two strings are equal, without regard to case. - - The expected string - The actual string - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that two strings are equal, without regard to case. - - The expected string - The actual string - The message to display in case of failure - - - - Asserts that two strings are equal, without regard to case. - - The expected string - The actual string - - - - Asserts that two strings are not equal, without regard to case. - - The expected string - The actual string - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that two strings are Notequal, without regard to case. - - The expected string - The actual string - The message to display in case of failure - - - - Asserts that two strings are not equal, without regard to case. - - The expected string - The actual string - - - - Asserts that a string matches an expected regular expression pattern. - - The regex pattern to be matched - The actual string - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string matches an expected regular expression pattern. - - The regex pattern to be matched - The actual string - The message to display in case of failure - - - - Asserts that a string matches an expected regular expression pattern. - - The regex pattern to be matched - The actual string - - - - Asserts that a string does not match an expected regular expression pattern. - - The regex pattern to be used - The actual string - The message to display in case of failure - Arguments used in formatting the message - - - - Asserts that a string does not match an expected regular expression pattern. - - The regex pattern to be used - The actual string - The message to display in case of failure - - - - Asserts that a string does not match an expected regular expression pattern. - - The regex pattern to be used - The actual string - - - - The TestCaseData class represents a set of arguments - and other parameter info to be used for a parameterized - test case. It provides a number of instance modifiers - for use in initializing the test case. - - Note: Instance modifiers are getters that return - the same instance after modifying it's state. - - - - - The argument list to be provided to the test - - - - - The expected result to be returned - - - - - Set to true if this has an expected result - - - - - The expected exception Type - - - - - The FullName of the expected exception - - - - - The name to be used for the test - - - - - The description of the test - - - - - A dictionary of properties, used to add information - to tests without requiring the class to change. - - - - - If true, indicates that the test case is to be ignored - - - - - If true, indicates that the test case is marked explicit - - - - - The reason for ignoring a test case - - - - - Initializes a new instance of the class. - - The arguments. - - - - Initializes a new instance of the class. - - The argument. - - - - Initializes a new instance of the class. - - The first argument. - The second argument. - - - - Initializes a new instance of the class. - - The first argument. - The second argument. - The third argument. - - - - Sets the expected result for the test - - The expected result - A modified TestCaseData - - - - Sets the expected exception type for the test - - Type of the expected exception. - The modified TestCaseData instance - - - - Sets the expected exception type for the test - - FullName of the expected exception. - The modified TestCaseData instance - - - - Sets the name of the test case - - The modified TestCaseData instance - - - - Sets the description for the test case - being constructed. - - The description. - The modified TestCaseData instance. - - - - Applies a category to the test - - - - - - - Applies a named property to the test - - - - - - - - Applies a named property to the test - - - - - - - - Applies a named property to the test - - - - - - - - Ignores this TestCase. - - - - - - Ignores this TestCase, specifying the reason. - - The reason. - - - - - Marks this TestCase as Explicit - - - - - - Marks this TestCase as Explicit, specifying the reason. - - The reason. - - - - - Gets the argument list to be provided to the test - - - - - Gets the expected result - - - - - Returns true if the result has been set - - - - - Gets the expected exception Type - - - - - Gets the FullName of the expected exception - - - - - Gets the name to be used for the test - - - - - Gets the description of the test - - - - - Gets a value indicating whether this is ignored. - - true if ignored; otherwise, false. - - - - Gets a value indicating whether this is explicit. - - true if explicit; otherwise, false. - - - - Gets the ignore reason. - - The ignore reason. - - - - Gets a list of categories associated with this test. - - - - - Gets the property dictionary for this test - - - - - Provide the context information of the current test - - - - - Constructs a TestContext using the provided context dictionary - - A context dictionary - - - - Get the current test context. This is created - as needed. The user may save the context for - use within a test, but it should not be used - outside the test for which it is created. - - - - - Gets a TestAdapter representing the currently executing test in this context. - - - - - Gets a ResultAdapter representing the current result for the test - executing in this context. - - - - - Gets the directory containing the current test assembly. - - - - - Gets the directory to be used for outputing files created - by this test run. - - - - - TestAdapter adapts a Test for consumption by - the user test code. - - - - - Constructs a TestAdapter for this context - - The context dictionary - - - - The name of the test. - - - - - The FullName of the test - - - - - The properties of the test. - - - - - ResultAdapter adapts a TestResult for consumption by - the user test code. - - - - - Construct a ResultAdapter for a context - - The context holding the result - - - - The TestState of current test. This maps to the ResultState - used in nunit.core and is subject to change in the future. - - - - - The TestStatus of current test. This enum will be used - in future versions of NUnit and so is to be preferred - to the TestState value. - - - - - Provides details about a test - - - - - Creates an instance of TestDetails - - The fixture that the test is a member of, if available. - The method that implements the test, if available. - The full name of the test. - A string representing the type of test, e.g. "Test Case". - Indicates if the test represents a suite of tests. - - - - The fixture that the test is a member of, if available. - - - - - The method that implements the test, if available. - - - - - The full name of the test. - - - - - A string representing the type of test, e.g. "Test Case". - - - - - Indicates if the test represents a suite of tests. - - - - - The ResultState enum indicates the result of running a test - - - - - The result is inconclusive - - - - - The test was not runnable. - - - - - The test has been skipped. - - - - - The test has been ignored. - - - - - The test succeeded - - - - - The test failed - - - - - The test encountered an unexpected exception - - - - - The test was cancelled by the user - - - - - The TestStatus enum indicates the result of running a test - - - - - The test was inconclusive - - - - - The test has skipped - - - - - The test succeeded - - - - - The test failed - - - - - Helper class with static methods used to supply constraints - that operate on strings. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that fails if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the Regex pattern supplied as an argument. - - - - - Returns a constraint that fails if the actual - value matches the pattern supplied as an argument. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them succeed. - - - - - TextMessageWriter writes constraint descriptions and messages - in displayable form as a text stream. It tailors the display - of individual message components to form the standard message - format of NUnit assertion failure messages. - - - - - MessageWriter is the abstract base for classes that write - constraint descriptions and messages in some form. The - class has separate methods for writing various components - of a message, allowing implementations to tailor the - presentation as needed. - - - - - Construct a MessageWriter given a culture - - - - - Method to write single line message with optional args, usually - written to precede the general failure message. - - The message to be written - Any arguments used in formatting the message - - - - Method to write single line message with optional args, usually - written to precede the general failure message, at a givel - indentation level. - - The indentation level of the message - The message to be written - Any arguments used in formatting the message - - - - Display Expected and Actual lines for a constraint. This - is called by MessageWriter's default implementation of - WriteMessageTo and provides the generic two-line display. - - The constraint that failed - - - - Display Expected and Actual lines for given values. This - method may be called by constraints that need more control over - the display of actual and expected values than is provided - by the default implementation. - - The expected value - The actual value causing the failure - - - - Display Expected and Actual lines for given values, including - a tolerance value on the Expected line. - - The expected value - The actual value causing the failure - The tolerance within which the test was made - - - - Display the expected and actual string values on separate lines. - If the mismatch parameter is >=0, an additional line is displayed - line containing a caret that points to the mismatch point. - - The expected string value - The actual string value - The point at which the strings don't match or -1 - If true, case is ignored in locating the point where the strings differ - If true, the strings should be clipped to fit the line - - - - Writes the text for a connector. - - The connector. - - - - Writes the text for a predicate. - - The predicate. - - - - Writes the text for an expected value. - - The expected value. - - - - Writes the text for a modifier - - The modifier. - - - - Writes the text for an actual value. - - The actual value. - - - - Writes the text for a generalized value. - - The value. - - - - Writes the text for a collection value, - starting at a particular point, to a max length - - The collection containing elements to write. - The starting point of the elements to write - The maximum number of elements to write - - - - Abstract method to get the max line length - - - - - Prefix used for the expected value line of a message - - - - - Prefix used for the actual value line of a message - - - - - Length of a message prefix - - - - - Construct a TextMessageWriter - - - - - Construct a TextMessageWriter, specifying a user message - and optional formatting arguments. - - - - - - - Method to write single line message with optional args, usually - written to precede the general failure message, at a givel - indentation level. - - The indentation level of the message - The message to be written - Any arguments used in formatting the message - - - - Display Expected and Actual lines for a constraint. This - is called by MessageWriter's default implementation of - WriteMessageTo and provides the generic two-line display. - - The constraint that failed - - - - Display Expected and Actual lines for given values. This - method may be called by constraints that need more control over - the display of actual and expected values than is provided - by the default implementation. - - The expected value - The actual value causing the failure - - - - Display Expected and Actual lines for given values, including - a tolerance value on the expected line. - - The expected value - The actual value causing the failure - The tolerance within which the test was made - - - - Display the expected and actual string values on separate lines. - If the mismatch parameter is >=0, an additional line is displayed - line containing a caret that points to the mismatch point. - - The expected string value - The actual string value - The point at which the strings don't match or -1 - If true, case is ignored in string comparisons - If true, clip the strings to fit the max line length - - - - Writes the text for a connector. - - The connector. - - - - Writes the text for a predicate. - - The predicate. - - - - Write the text for a modifier. - - The modifier. - - - - Writes the text for an expected value. - - The expected value. - - - - Writes the text for an actual value. - - The actual value. - - - - Writes the text for a generalized value. - - The value. - - - - Writes the text for a collection value, - starting at a particular point, to a max length - - The collection containing elements to write. - The starting point of the elements to write - The maximum number of elements to write - - - - Write the generic 'Expected' line for a constraint - - The constraint that failed - - - - Write the generic 'Expected' line for a given value - - The expected value - - - - Write the generic 'Expected' line for a given value - and tolerance. - - The expected value - The tolerance within which the test was made - - - - Write the generic 'Actual' line for a constraint - - The constraint for which the actual value is to be written - - - - Write the generic 'Actual' line for a given value - - The actual value causing a failure - - - - Gets or sets the maximum line length for this writer - - - - - Helper class with properties and methods that supply - constraints that operate on exceptions. - - - - - Creates a constraint specifying the exact type of exception expected - - - - - Creates a constraint specifying the exact type of exception expected - - - - - Creates a constraint specifying the type of exception expected - - - - - Creates a constraint specifying the type of exception expected - - - - - Creates a constraint specifying an expected exception - - - - - Creates a constraint specifying an exception with a given InnerException - - - - - Creates a constraint specifying an expected TargetInvocationException - - - - - Creates a constraint specifying an expected TargetInvocationException - - - - - Creates a constraint specifying an expected TargetInvocationException - - - - - Creates a constraint specifying that no exception is thrown - - - - - Attribute used to apply a category to a test - - - - - The name of the category - - - - - Construct attribute for a given category based on - a name. The name may not contain the characters ',', - '+', '-' or '!'. However, this is not checked in the - constructor since it would cause an error to arise at - as the test was loaded without giving a clear indication - of where the problem is located. The error is handled - in NUnitFramework.cs by marking the test as not - runnable. - - The name of the category - - - - Protected constructor uses the Type name as the name - of the category. - - - - - The name of the category - - - - - Used to mark a field for use as a datapoint when executing a theory - within the same fixture that requires an argument of the field's Type. - - - - - Used to mark an array as containing a set of datapoints to be used - executing a theory within the same fixture that requires an argument - of the Type of the array elements. - - - - - Attribute used to provide descriptive text about a - test case or fixture. - - - - - Construct the attribute - - Text describing the test - - - - Gets the test description - - - - - Enumeration indicating how the expected message parameter is to be used - - - - Expect an exact match - - - Expect a message containing the parameter string - - - Match the regular expression provided as a parameter - - - Expect a message that starts with the parameter string - - - - ExpectedExceptionAttribute - - - - - - Constructor for a non-specific exception - - - - - Constructor for a given type of exception - - The type of the expected exception - - - - Constructor for a given exception name - - The full name of the expected exception - - - - Gets or sets the expected exception type - - - - - Gets or sets the full Type name of the expected exception - - - - - Gets or sets the expected message text - - - - - Gets or sets the user message displayed in case of failure - - - - - Gets or sets the type of match to be performed on the expected message - - - - - Gets the name of a method to be used as an exception handler - - - - - ExplicitAttribute marks a test or test fixture so that it will - only be run if explicitly executed from the gui or command line - or if it is included by use of a filter. The test will not be - run simply because an enclosing suite is run. - - - - - Default constructor - - - - - Constructor with a reason - - The reason test is marked explicit - - - - The reason test is marked explicit - - - - - Attribute used to mark a test that is to be ignored. - Ignored tests result in a warning message when the - tests are run. - - - - - Constructs the attribute without giving a reason - for ignoring the test. - - - - - Constructs the attribute giving a reason for ignoring the test - - The reason for ignoring the test - - - - The reason for ignoring a test - - - - - Abstract base for Attributes that are used to include tests - in the test run based on environmental settings. - - - - - Constructor with no included items specified, for use - with named property syntax. - - - - - Constructor taking one or more included items - - Comma-delimited list of included items - - - - Name of the item that is needed in order for - a test to run. Multiple itemss may be given, - separated by a comma. - - - - - Name of the item to be excluded. Multiple items - may be given, separated by a comma. - - - - - The reason for including or excluding the test - - - - - PlatformAttribute is used to mark a test fixture or an - individual method as applying to a particular platform only. - - - - - Constructor with no platforms specified, for use - with named property syntax. - - - - - Constructor taking one or more platforms - - Comma-deliminted list of platforms - - - - CultureAttribute is used to mark a test fixture or an - individual method as applying to a particular Culture only. - - - - - Constructor with no cultures specified, for use - with named property syntax. - - - - - Constructor taking one or more cultures - - Comma-deliminted list of cultures - - - - Marks a test to use a combinatorial join of any argument data - provided. NUnit will create a test case for every combination of - the arguments provided. This can result in a large number of test - cases and so should be used judiciously. This is the default join - type, so the attribute need not be used except as documentation. - - - - - PropertyAttribute is used to attach information to a test as a name/value pair.. - - - - - Construct a PropertyAttribute with a name and string value - - The name of the property - The property value - - - - Construct a PropertyAttribute with a name and int value - - The name of the property - The property value - - - - Construct a PropertyAttribute with a name and double value - - The name of the property - The property value - - - - Constructor for derived classes that set the - property dictionary directly. - - - - - Constructor for use by derived classes that use the - name of the type as the property name. Derived classes - must ensure that the Type of the property value is - a standard type supported by the BCL. Any custom - types will cause a serialization Exception when - in the client. - - - - - Gets the property dictionary for this attribute - - - - - Default constructor - - - - - Marks a test to use pairwise join of any argument data provided. - NUnit will attempt too excercise every pair of argument values at - least once, using as small a number of test cases as it can. With - only two arguments, this is the same as a combinatorial join. - - - - - Default constructor - - - - - Marks a test to use a sequential join of any argument data - provided. NUnit will use arguements for each parameter in - sequence, generating test cases up to the largest number - of argument values provided and using null for any arguments - for which it runs out of values. Normally, this should be - used with the same number of arguments for each parameter. - - - - - Default constructor - - - - - Summary description for MaxTimeAttribute. - - - - - Construct a MaxTimeAttribute, given a time in milliseconds. - - The maximum elapsed time in milliseconds - - - - RandomAttribute is used to supply a set of random values - to a single parameter of a parameterized test. - - - - - ValuesAttribute is used to provide literal arguments for - an individual parameter of a test. - - - - - Abstract base class for attributes that apply to parameters - and supply data for the parameter. - - - - - Gets the data to be provided to the specified parameter - - - - - The collection of data to be returned. Must - be set by any derived attribute classes. - We use an object[] so that the individual - elements may have their type changed in GetData - if necessary. - - - - - Construct with one argument - - - - - - Construct with two arguments - - - - - - - Construct with three arguments - - - - - - - - Construct with an array of arguments - - - - - - Get the collection of values to be used as arguments - - - - - Construct a set of doubles from 0.0 to 1.0, - specifying only the count. - - - - - - Construct a set of doubles from min to max - - - - - - - - Construct a set of ints from min to max - - - - - - - - Get the collection of values to be used as arguments - - - - - RangeAttribute is used to supply a range of values to an - individual parameter of a parameterized test. - - - - - Construct a range of ints using default step of 1 - - - - - - - Construct a range of ints specifying the step size - - - - - - - - Construct a range of longs - - - - - - - - Construct a range of doubles - - - - - - - - Construct a range of floats - - - - - - - - RepeatAttribute may be applied to test case in order - to run it multiple times. - - - - - Construct a RepeatAttribute - - The number of times to run the test - - - - RequiredAddinAttribute may be used to indicate the names of any addins - that must be present in order to run some or all of the tests in an - assembly. If the addin is not loaded, the entire assembly is marked - as NotRunnable. - - - - - Initializes a new instance of the class. - - The required addin. - - - - Gets the name of required addin. - - The required addin name. - - - - Summary description for SetCultureAttribute. - - - - - Construct given the name of a culture - - - - - - Summary description for SetUICultureAttribute. - - - - - Construct given the name of a culture - - - - - - SetUpAttribute is used in a TestFixture to identify a method - that is called immediately before each test is run. It is - also used in a SetUpFixture to identify the method that is - called once, before any of the subordinate tests are run. - - - - - Attribute used to mark a class that contains one-time SetUp - and/or TearDown methods that apply to all the tests in a - namespace or an assembly. - - - - - Attribute used to mark a static (shared in VB) property - that returns a list of tests. - - - - - Attribute used in a TestFixture to identify a method that is - called immediately after each test is run. It is also used - in a SetUpFixture to identify the method that is called once, - after all subordinate tests have run. In either case, the method - is guaranteed to be called, even if an exception is thrown. - - - - - Provide actions to execute before and after tests. - - - - - When implemented by an attribute, this interface implemented to provide actions to execute before and after tests. - - - - - Executed before each test is run - - Provides details about the test that is going to be run. - - - - Executed after each test is run - - Provides details about the test that has just been run. - - - - Provides the target for the action attribute - - The target for the action attribute - - - - Method called before each test - - Info about the test to be run - - - - Method called after each test - - Info about the test that was just run - - - - Gets or sets the ActionTargets for this attribute - - - - - Adding this attribute to a method within a - class makes the method callable from the NUnit test runner. There is a property - called Description which is optional which you can provide a more detailed test - description. This class cannot be inherited. - - - - [TestFixture] - public class Fixture - { - [Test] - public void MethodToTest() - {} - - [Test(Description = "more detailed description")] - publc void TestDescriptionMethod() - {} - } - - - - - - Descriptive text for this test - - - - - TestCaseAttribute is used to mark parameterized test cases - and provide them with their arguments. - - - - - Construct a TestCaseAttribute with a list of arguments. - This constructor is not CLS-Compliant - - - - - - Construct a TestCaseAttribute with a single argument - - - - - - Construct a TestCaseAttribute with a two arguments - - - - - - - Construct a TestCaseAttribute with a three arguments - - - - - - - - Gets the list of arguments to a test case - - - - - Gets or sets the expected result. Use - ExpectedResult by preference. - - The result. - - - - Gets or sets the expected result. - - The result. - - - - Gets a flag indicating whether an expected - result has been set. - - - - - Gets a list of categories associated with this test; - - - - - Gets or sets the category associated with this test. - May be a single category or a comma-separated list. - - - - - Gets or sets the expected exception. - - The expected exception. - - - - Gets or sets the name the expected exception. - - The expected name of the exception. - - - - Gets or sets the expected message of the expected exception - - The expected message of the exception. - - - - Gets or sets the type of match to be performed on the expected message - - - - - Gets or sets the description. - - The description. - - - - Gets or sets the name of the test. - - The name of the test. - - - - Gets or sets the ignored status of the test - - - - - Gets or sets the ignored status of the test - - - - - Gets or sets the explicit status of the test - - - - - Gets or sets the reason for not running the test - - - - - Gets or sets the reason for not running the test. - Set has the side effect of marking the test as ignored. - - The ignore reason. - - - - FactoryAttribute indicates the source to be used to - provide test cases for a test method. - - - - - Construct with the name of the data source, which must - be a property, field or method of the test class itself. - - An array of the names of the factories that will provide data - - - - Construct with a Type, which must implement IEnumerable - - The Type that will provide data - - - - Construct with a Type and name. - that don't support params arrays. - - The Type that will provide data - The name of the method, property or field that will provide data - - - - The name of a the method, property or fiend to be used as a source - - - - - A Type to be used as a source - - - - - Gets or sets the category associated with this test. - May be a single category or a comma-separated list. - - - - - [TestFixture] - public class ExampleClass - {} - - - - - Default constructor - - - - - Construct with a object[] representing a set of arguments. - In .NET 2.0, the arguments may later be separated into - type arguments and constructor arguments. - - - - - - Descriptive text for this fixture - - - - - Gets and sets the category for this fixture. - May be a comma-separated list of categories. - - - - - Gets a list of categories for this fixture - - - - - The arguments originally provided to the attribute - - - - - Gets or sets a value indicating whether this should be ignored. - - true if ignore; otherwise, false. - - - - Gets or sets the ignore reason. May set Ignored as a side effect. - - The ignore reason. - - - - Get or set the type arguments. If not set - explicitly, any leading arguments that are - Types are taken as type arguments. - - - - - Attribute used to identify a method that is - called before any tests in a fixture are run. - - - - - Attribute used to identify a method that is called after - all the tests in a fixture have run. The method is - guaranteed to be called, even if an exception is thrown. - - - - - Adding this attribute to a method within a - class makes the method callable from the NUnit test runner. There is a property - called Description which is optional which you can provide a more detailed test - description. This class cannot be inherited. - - - - [TestFixture] - public class Fixture - { - [Test] - public void MethodToTest() - {} - - [Test(Description = "more detailed description")] - publc void TestDescriptionMethod() - {} - } - - - - - - Used on a method, marks the test with a timeout value in milliseconds. - The test will be run in a separate thread and is cancelled if the timeout - is exceeded. Used on a method or assembly, sets the default timeout - for all contained test methods. - - - - - Construct a TimeoutAttribute given a time in milliseconds - - The timeout value in milliseconds - - - - Marks a test that must run in the STA, causing it - to run in a separate thread if necessary. - - On methods, you may also use STAThreadAttribute - to serve the same purpose. - - - - - Construct a RequiresSTAAttribute - - - - - Marks a test that must run in the MTA, causing it - to run in a separate thread if necessary. - - On methods, you may also use MTAThreadAttribute - to serve the same purpose. - - - - - Construct a RequiresMTAAttribute - - - - - Marks a test that must run on a separate thread. - - - - - Construct a RequiresThreadAttribute - - - - - Construct a RequiresThreadAttribute, specifying the apartment - - - - - ValueSourceAttribute indicates the source to be used to - provide data for one parameter of a test method. - - - - - Construct with the name of the factory - for use with languages - that don't support params arrays. - - The name of the data source to be used - - - - Construct with a Type and name - for use with languages - that don't support params arrays. - - The Type that will provide data - The name of the method, property or field that will provide data - - - - The name of a the method, property or fiend to be used as a source - - - - - A Type to be used as a source - - - - - AllItemsConstraint applies another constraint to each - item in a collection, succeeding if they all succeed. - - - - - Abstract base class used for prefixes - - - - - The Constraint class is the base of all built-in constraints - within NUnit. It provides the operator overloads used to combine - constraints. - - - - - The IConstraintExpression interface is implemented by all - complete and resolvable constraints and expressions. - - - - - Return the top-level constraint for this expression - - - - - - Static UnsetObject used to detect derived constraints - failing to set the actual value. - - - - - The actual value being tested against a constraint - - - - - The display name of this Constraint for use by ToString() - - - - - Argument fields used by ToString(); - - - - - The builder holding this constraint - - - - - Construct a constraint with no arguments - - - - - Construct a constraint with one argument - - - - - Construct a constraint with two arguments - - - - - Sets the ConstraintBuilder holding this constraint - - - - - Write the failure message to the MessageWriter provided - as an argument. The default implementation simply passes - the constraint and the actual value to the writer, which - then displays the constraint description and the value. - - Constraints that need to provide additional details, - such as where the error occured can override this. - - The MessageWriter on which to display the message - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Test whether the constraint is satisfied by an - ActualValueDelegate that returns the value to be tested. - The default implementation simply evaluates the delegate - but derived classes may override it to provide for delayed - processing. - - An - True for success, false for failure - - - - Test whether the constraint is satisfied by a given reference. - The default implementation simply dereferences the value but - derived classes may override it to provide for delayed processing. - - A reference to the value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - Default override of ToString returns the constraint DisplayName - followed by any arguments within angle brackets. - - - - - - Returns the string representation of this constraint - - - - - This operator creates a constraint that is satisfied only if both - argument constraints are satisfied. - - - - - This operator creates a constraint that is satisfied if either - of the argument constraints is satisfied. - - - - - This operator creates a constraint that is satisfied if the - argument constraint is not satisfied. - - - - - Returns a DelayedConstraint with the specified delay time. - - The delay in milliseconds. - - - - - Returns a DelayedConstraint with the specified delay time - and polling interval. - - The delay in milliseconds. - The interval at which to test the constraint. - - - - - The display name of this Constraint for use by ToString(). - The default value is the name of the constraint with - trailing "Constraint" removed. Derived classes may set - this to another name in their constructors. - - - - - Returns a ConstraintExpression by appending And - to the current constraint. - - - - - Returns a ConstraintExpression by appending And - to the current constraint. - - - - - Returns a ConstraintExpression by appending Or - to the current constraint. - - - - - Class used to detect any derived constraints - that fail to set the actual value in their - Matches override. - - - - - The base constraint - - - - - Construct given a base constraint - - - - - - Construct an AllItemsConstraint on top of an existing constraint - - - - - - Apply the item constraint to each item in the collection, - failing if any item fails. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - AndConstraint succeeds only if both members succeed. - - - - - BinaryConstraint is the abstract base of all constraints - that combine two other constraints in some fashion. - - - - - The first constraint being combined - - - - - The second constraint being combined - - - - - Construct a BinaryConstraint from two other constraints - - The first constraint - The second constraint - - - - Create an AndConstraint from two other constraints - - The first constraint - The second constraint - - - - Apply both member constraints to an actual value, succeeding - succeeding only if both of them succeed. - - The actual value - True if the constraints both succeeded - - - - Write a description for this contraint to a MessageWriter - - The MessageWriter to receive the description - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - AssignableFromConstraint is used to test that an object - can be assigned from a given Type. - - - - - TypeConstraint is the abstract base for constraints - that take a Type as their expected value. - - - - - The expected Type used by the constraint - - - - - Construct a TypeConstraint for a given Type - - - - - - Write the actual value for a failing constraint test to a - MessageWriter. TypeConstraints override this method to write - the name of the type. - - The writer on which the actual value is displayed - - - - Construct an AssignableFromConstraint for the type provided - - - - - - Test whether an object can be assigned from the specified type - - The object to be tested - True if the object can be assigned a value of the expected Type, otherwise false. - - - - Write a description of this constraint to a MessageWriter - - The MessageWriter to use - - - - AssignableToConstraint is used to test that an object - can be assigned to a given Type. - - - - - Construct an AssignableToConstraint for the type provided - - - - - - Test whether an object can be assigned to the specified type - - The object to be tested - True if the object can be assigned a value of the expected Type, otherwise false. - - - - Write a description of this constraint to a MessageWriter - - The MessageWriter to use - - - - AttributeConstraint tests that a specified attribute is present - on a Type or other provider and that the value of the attribute - satisfies some other constraint. - - - - - Constructs an AttributeConstraint for a specified attriute - Type and base constraint. - - - - - - - Determines whether the Type or other provider has the - expected attribute and if its value matches the - additional constraint specified. - - - - - Writes a description of the attribute to the specified writer. - - - - - Writes the actual value supplied to the specified writer. - - - - - Returns a string representation of the constraint. - - - - - AttributeExistsConstraint tests for the presence of a - specified attribute on a Type. - - - - - Constructs an AttributeExistsConstraint for a specific attribute Type - - - - - - Tests whether the object provides the expected attribute. - - A Type, MethodInfo, or other ICustomAttributeProvider - True if the expected attribute is present, otherwise false - - - - Writes the description of the constraint to the specified writer - - - - - BasicConstraint is the abstract base for constraints that - perform a simple comparison to a constant value. - - - - - Initializes a new instance of the class. - - The expected. - The description. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - BinarySerializableConstraint tests whether - an object is serializable in binary format. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - Returns the string representation - - - - - CollectionConstraint is the abstract base class for - constraints that operate on collections. - - - - - Construct an empty CollectionConstraint - - - - - Construct a CollectionConstraint - - - - - - Determines whether the specified enumerable is empty. - - The enumerable. - - true if the specified enumerable is empty; otherwise, false. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Protected method to be implemented by derived classes - - - - - - - CollectionContainsConstraint is used to test whether a collection - contains an expected object as a member. - - - - - CollectionItemsEqualConstraint is the abstract base class for all - collection constraints that apply some notion of item equality - as a part of their operation. - - - - - Construct an empty CollectionConstraint - - - - - Construct a CollectionConstraint - - - - - - Flag the constraint to use the supplied EqualityAdapter. - NOTE: For internal use only. - - The EqualityAdapter to use. - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied Comparison object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Compares two collection members for equality - - - - - Return a new CollectionTally for use in making tests - - The collection to be included in the tally - - - - Flag the constraint to ignore case and return self. - - - - - Construct a CollectionContainsConstraint - - - - - - Test whether the expected item is contained in the collection - - - - - - - Write a descripton of the constraint to a MessageWriter - - - - - - CollectionEquivalentCOnstraint is used to determine whether two - collections are equivalent. - - - - - Construct a CollectionEquivalentConstraint - - - - - - Test whether two collections are equivalent - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - CollectionOrderedConstraint is used to test whether a collection is ordered. - - - - - Construct a CollectionOrderedConstraint - - - - - Modifies the constraint to use an IComparer and returns self. - - - - - Modifies the constraint to use an IComparer<T> and returns self. - - - - - Modifies the constraint to use a Comparison<T> and returns self. - - - - - Modifies the constraint to test ordering by the value of - a specified property and returns self. - - - - - Test whether the collection is ordered - - - - - - - Write a description of the constraint to a MessageWriter - - - - - - Returns the string representation of the constraint. - - - - - - If used performs a reverse comparison - - - - - CollectionSubsetConstraint is used to determine whether - one collection is a subset of another - - - - - Construct a CollectionSubsetConstraint - - The collection that the actual value is expected to be a subset of - - - - Test whether the actual collection is a subset of - the expected collection provided. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - CollectionTally counts (tallies) the number of - occurences of each object in one or more enumerations. - - - - - Construct a CollectionTally object from a comparer and a collection - - - - - Try to remove an object from the tally - - The object to remove - True if successful, false if the object was not found - - - - Try to remove a set of objects from the tally - - The objects to remove - True if successful, false if any object was not found - - - - The number of objects remaining in the tally - - - - - ComparisonAdapter class centralizes all comparisons of - values in NUnit, adapting to the use of any provided - IComparer, IComparer<T> or Comparison<T> - - - - - Returns a ComparisonAdapter that wraps an IComparer - - - - - Returns a ComparisonAdapter that wraps an IComparer<T> - - - - - Returns a ComparisonAdapter that wraps a Comparison<T> - - - - - Compares two objects - - - - - Gets the default ComparisonAdapter, which wraps an - NUnitComparer object. - - - - - Construct a ComparisonAdapter for an IComparer - - - - - Compares two objects - - - - - - - - Construct a default ComparisonAdapter - - - - - ComparisonAdapter<T> extends ComparisonAdapter and - allows use of an IComparer<T> or Comparison<T> - to actually perform the comparison. - - - - - Construct a ComparisonAdapter for an IComparer<T> - - - - - Compare a Type T to an object - - - - - Construct a ComparisonAdapter for a Comparison<T> - - - - - Compare a Type T to an object - - - - - Abstract base class for constraints that compare values to - determine if one is greater than, equal to or less than - the other. This class supplies the Using modifiers. - - - - - ComparisonAdapter to be used in making the comparison - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - - - - Modifies the constraint to use an IComparer and returns self - - - - - Modifies the constraint to use an IComparer<T> and returns self - - - - - Modifies the constraint to use a Comparison<T> and returns self - - - - - Delegate used to delay evaluation of the actual value - to be used in evaluating a constraint - - - - - ConstraintBuilder maintains the stacks that are used in - processing a ConstraintExpression. An OperatorStack - is used to hold operators that are waiting for their - operands to be reognized. a ConstraintStack holds - input constraints as well as the results of each - operator applied. - - - - - Initializes a new instance of the class. - - - - - Appends the specified operator to the expression by first - reducing the operator stack and then pushing the new - operator on the stack. - - The operator to push. - - - - Appends the specified constraint to the expresson by pushing - it on the constraint stack. - - The constraint to push. - - - - Sets the top operator right context. - - The right context. - - - - Reduces the operator stack until the topmost item - precedence is greater than or equal to the target precedence. - - The target precedence. - - - - Resolves this instance, returning a Constraint. If the builder - is not currently in a resolvable state, an exception is thrown. - - The resolved constraint - - - - Gets a value indicating whether this instance is resolvable. - - - true if this instance is resolvable; otherwise, false. - - - - - OperatorStack is a type-safe stack for holding ConstraintOperators - - - - - Initializes a new instance of the class. - - The builder. - - - - Pushes the specified operator onto the stack. - - The op. - - - - Pops the topmost operator from the stack. - - - - - - Gets a value indicating whether this is empty. - - true if empty; otherwise, false. - - - - Gets the topmost operator without modifying the stack. - - The top. - - - - ConstraintStack is a type-safe stack for holding Constraints - - - - - Initializes a new instance of the class. - - The builder. - - - - Pushes the specified constraint. As a side effect, - the constraint's builder field is set to the - ConstraintBuilder owning this stack. - - The constraint. - - - - Pops this topmost constrait from the stack. - As a side effect, the constraint's builder - field is set to null. - - - - - - Gets a value indicating whether this is empty. - - true if empty; otherwise, false. - - - - Gets the topmost constraint without modifying the stack. - - The topmost constraint - - - - ConstraintExpression represents a compound constraint in the - process of being constructed from a series of syntactic elements. - - Individual elements are appended to the expression as they are - reognized. Once an actual Constraint is appended, the expression - returns a resolvable Constraint. - - - - - ConstraintExpressionBase is the abstract base class for the - ConstraintExpression class, which represents a - compound constraint in the process of being constructed - from a series of syntactic elements. - - NOTE: ConstraintExpressionBase is separate because the - ConstraintExpression class was generated in earlier - versions of NUnit. The two classes may be combined - in a future version. - - - - - The ConstraintBuilder holding the elements recognized so far - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the - class passing in a ConstraintBuilder, which may be pre-populated. - - The builder. - - - - Returns a string representation of the expression as it - currently stands. This should only be used for testing, - since it has the side-effect of resolving the expression. - - - - - - Appends an operator to the expression and returns the - resulting expression itself. - - - - - Appends a self-resolving operator to the expression and - returns a new ResolvableConstraintExpression. - - - - - Appends a constraint to the expression and returns that - constraint, which is associated with the current state - of the expression being built. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the - class passing in a ConstraintBuilder, which may be pre-populated. - - The builder. - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding only if a specified number of them succeed. - - - - - Returns a new PropertyConstraintExpression, which will either - test for the existence of the named property on the object - being tested or apply any following constraint to that property. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns a new AttributeConstraint checking for the - presence of a particular attribute on an object. - - - - - Returns the constraint provided as an argument - used to allow custom - custom constraints to easily participate in the syntax. - - - - - Returns the constraint provided as an argument - used to allow custom - custom constraints to easily participate in the syntax. - - - - - Returns a constraint that tests two items for equality - - - - - Returns a constraint that tests that two references are the same object - - - - - Returns a constraint that tests whether the - actual value is greater than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is greater than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the - actual value is less than or equal to the suppled argument - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual - value is of the exact type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is of the type supplied as an argument or a derived type. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is assignable from the type supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a collection containing the same elements as the - collection supplied as an argument. - - - - - Returns a constraint that tests whether the actual value - is a subset of the collection supplied as an argument. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a new CollectionContainsConstraint checking for the - presence of a particular object in the collection. - - - - - Returns a new ContainsConstraint. This constraint - will, in turn, make use of the appropriate second-level - constraint, depending on the type of the actual argument. - This overload is only used if the item sought is a string, - since any other type implies that we are looking for a - collection member. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value contains the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value starts with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value ends with the substring supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the regular expression supplied as an argument. - - - - - Returns a constraint that succeeds if the actual - value matches the regular expression supplied as an argument. - - - - - Returns a constraint that tests whether the path provided - is the same as an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is the same path or under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the path provided - is the same path or under an expected path after canonicalization. - - - - - Returns a constraint that tests whether the actual value falls - within a specified range. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression that negates any - following constraint. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them succeed. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if at least one of them succeeds. - - - - - Returns a ConstraintExpression, which will apply - the following constraint to all members of a collection, - succeeding if all of them fail. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Length property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Count property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the Message property of the object being tested. - - - - - Returns a new ConstraintExpression, which will apply the following - constraint to the InnerException property of the object being tested. - - - - - With is currently a NOP - reserved for future use. - - - - - Returns a constraint that tests for null - - - - - Returns a constraint that tests for True - - - - - Returns a constraint that tests for False - - - - - Returns a constraint that tests for a positive value - - - - - Returns a constraint that tests for a negative value - - - - - Returns a constraint that tests for NaN - - - - - Returns a constraint that tests for empty - - - - - Returns a constraint that tests whether a collection - contains all unique items. - - - - - Returns a constraint that tests whether an object graph is serializable in binary format. - - - - - Returns a constraint that tests whether an object graph is serializable in xml format. - - - - - Returns a constraint that tests whether a collection is ordered - - - - - ContainsConstraint tests a whether a string contains a substring - or a collection contains an object. It postpones the decision of - which test to use until the type of the actual argument is known. - This allows testing whether a string is contained in a collection - or as a substring of another string using the same syntax. - - - - - Initializes a new instance of the class. - - The expected. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied Comparison object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to ignore case and return self. - - - - - Applies a delay to the match so that a match can be evaluated in the future. - - - - - Creates a new DelayedConstraint - - The inner constraint two decorate - The time interval after which the match is performed - If the value of is less than 0 - - - - Creates a new DelayedConstraint - - The inner constraint two decorate - The time interval after which the match is performed - The time interval used for polling - If the value of is less than 0 - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for if the base constraint fails, false if it succeeds - - - - Test whether the constraint is satisfied by a delegate - - The delegate whose value is to be tested - True for if the base constraint fails, false if it succeeds - - - - Test whether the constraint is satisfied by a given reference. - Overridden to wait for the specified delay period before - calling the base constraint with the dereferenced value. - - A reference to the value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a MessageWriter. - - The writer on which the actual value is displayed - - - - Returns the string representation of the constraint. - - - - - EmptyCollectionConstraint tests whether a collection is empty. - - - - - Check that the collection is empty - - - - - - - Write the constraint description to a MessageWriter - - - - - - EmptyConstraint tests a whether a string or collection is empty, - postponing the decision about which test is applied until the - type of the actual argument is known. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - EmptyDirectoryConstraint is used to test that a directory is empty - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - EmptyStringConstraint tests whether a string is empty. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - EndsWithConstraint can test whether a string ends - with an expected substring. - - - - - StringConstraint is the abstract base for constraints - that operate on strings. It supports the IgnoreCase - modifier for string operations. - - - - - The expected value - - - - - Indicates whether tests should be case-insensitive - - - - - Constructs a StringConstraint given an expected value - - The expected value - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Test whether the constraint is satisfied by a given string - - The string to be tested - True for success, false for failure - - - - Modify the constraint to ignore case in matching. - - - - - Initializes a new instance of the class. - - The expected string - - - - Test whether the constraint is matched by the actual value. - This is a template method, which calls the IsMatch method - of the derived class. - - - - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - EqualConstraint is able to compare an actual value with the - expected value provided in its constructor. Two objects are - considered equal if both are null, or if both have the same - value. NUnit has special semantics for some object types. - - - - - If true, strings in error messages will be clipped - - - - - NUnitEqualityComparer used to test equality. - - - - - Initializes a new instance of the class. - - The expected value. - - - - Flag the constraint to use a tolerance when determining equality. - - Tolerance value to be used - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied Comparison object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Flag the constraint to use the supplied IEqualityComparer object. - - The IComparer object to use. - Self. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write a failure message. Overridden to provide custom - failure messages for EqualConstraint. - - The MessageWriter to write to - - - - Write description of this constraint - - The MessageWriter to write to - - - - Display the failure information for two collections that did not match. - - The MessageWriter on which to display - The expected collection. - The actual collection - The depth of this failure in a set of nested collections - - - - Displays a single line showing the types and sizes of the expected - and actual enumerations, collections or arrays. If both are identical, - the value is only shown once. - - The MessageWriter on which to display - The expected collection or array - The actual collection or array - The indentation level for the message line - - - - Displays a single line showing the point in the expected and actual - arrays at which the comparison failed. If the arrays have different - structures or dimensions, both values are shown. - - The MessageWriter on which to display - The expected array - The actual array - Index of the failure point in the underlying collections - The indentation level for the message line - - - - Display the failure information for two IEnumerables that did not match. - - The MessageWriter on which to display - The expected enumeration. - The actual enumeration - The depth of this failure in a set of nested collections - - - - Flag the constraint to ignore case and return self. - - - - - Flag the constraint to suppress string clipping - and return self. - - - - - Flag the constraint to compare arrays as collections - and return self. - - - - - Switches the .Within() modifier to interpret its tolerance as - a distance in representable values (see remarks). - - Self. - - Ulp stands for "unit in the last place" and describes the minimum - amount a given value can change. For any integers, an ulp is 1 whole - digit. For floating point values, the accuracy of which is better - for smaller numbers and worse for larger numbers, an ulp depends - on the size of the number. Using ulps for comparison of floating - point results instead of fixed tolerances is safer because it will - automatically compensate for the added inaccuracy of larger numbers. - - - - - Switches the .Within() modifier to interpret its tolerance as - a percentage that the actual values is allowed to deviate from - the expected value. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in days. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in hours. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in minutes. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in seconds. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in milliseconds. - - Self - - - - Causes the tolerance to be interpreted as a TimeSpan in clock ticks. - - Self - - - - EqualityAdapter class handles all equality comparisons - that use an IEqualityComparer, IEqualityComparer<T> - or a ComparisonAdapter. - - - - - Compares two objects, returning true if they are equal - - - - - Returns true if the two objects can be compared by this adapter. - The base adapter cannot handle IEnumerables except for strings. - - - - - Returns an EqualityAdapter that wraps an IComparer. - - - - - Returns an EqualityAdapter that wraps an IEqualityComparer. - - - - - Returns an EqualityAdapter that wraps an IEqualityComparer<T>. - - - - - Returns an EqualityAdapter that wraps an IComparer<T>. - - - - - Returns an EqualityAdapter that wraps a Comparison<T>. - - - - - EqualityAdapter that wraps an IComparer. - - - - - Returns true if the two objects can be compared by this adapter. - Generic adapter requires objects of the specified type. - - - - - EqualityAdapter that wraps an IComparer. - - - - - EqualityAdapterList represents a list of EqualityAdapters - in a common class across platforms. - - - - - ExactCountConstraint applies another constraint to each - item in a collection, succeeding only if a specified - number of items succeed. - - - - - Construct an ExactCountConstraint on top of an existing constraint - - - - - - - Apply the item constraint to each item in the collection, - succeeding only if the expected number of items pass. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - ExactTypeConstraint is used to test that an object - is of the exact type provided in the constructor - - - - - Construct an ExactTypeConstraint for a given Type - - The expected Type. - - - - Test that an object is of the exact type specified - - The actual value. - True if the tested object is of the exact type provided, otherwise false. - - - - Write the description of this constraint to a MessageWriter - - The MessageWriter to use - - - - ExceptionTypeConstraint is a special version of ExactTypeConstraint - used to provided detailed info about the exception thrown in - an error message. - - - - - Constructs an ExceptionTypeConstraint - - - - - Write the actual value for a failing constraint test to a - MessageWriter. Overriden to write additional information - in the case of an Exception. - - The MessageWriter to use - - - - FailurePoint class represents one point of failure - in an equality test. - - - - - The location of the failure - - - - - The expected value - - - - - The actual value - - - - - Indicates whether the expected value is valid - - - - - Indicates whether the actual value is valid - - - - - FailurePointList represents a set of FailurePoints - in a cross-platform way. - - - - - FalseConstraint tests that the actual value is false - - - - - Initializes a new instance of the class. - - - - Helper routines for working with floating point numbers - - - The floating point comparison code is based on this excellent article: - http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm - - - "ULP" means Unit in the Last Place and in the context of this library refers to - the distance between two adjacent floating point numbers. IEEE floating point - numbers can only represent a finite subset of natural numbers, with greater - accuracy for smaller numbers and lower accuracy for very large numbers. - - - If a comparison is allowed "2 ulps" of deviation, that means the values are - allowed to deviate by up to 2 adjacent floating point values, which might be - as low as 0.0000001 for small numbers or as high as 10.0 for large numbers. - - - - - Compares two floating point values for equality - First floating point value to be compared - Second floating point value t be compared - - Maximum number of representable floating point values that are allowed to - be between the left and the right floating point values - - True if both numbers are equal or close to being equal - - - Floating point values can only represent a finite subset of natural numbers. - For example, the values 2.00000000 and 2.00000024 can be stored in a float, - but nothing inbetween them. - - - This comparison will count how many possible floating point values are between - the left and the right number. If the number of possible values between both - numbers is less than or equal to maxUlps, then the numbers are considered as - being equal. - - - Implementation partially follows the code outlined here: - http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ - - - - - Compares two double precision floating point values for equality - First double precision floating point value to be compared - Second double precision floating point value t be compared - - Maximum number of representable double precision floating point values that are - allowed to be between the left and the right double precision floating point values - - True if both numbers are equal or close to being equal - - - Double precision floating point values can only represent a limited series of - natural numbers. For example, the values 2.0000000000000000 and 2.0000000000000004 - can be stored in a double, but nothing inbetween them. - - - This comparison will count how many possible double precision floating point - values are between the left and the right number. If the number of possible - values between both numbers is less than or equal to maxUlps, then the numbers - are considered as being equal. - - - Implementation partially follows the code outlined here: - http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ - - - - - - Reinterprets the memory contents of a floating point value as an integer value - - - Floating point value whose memory contents to reinterpret - - - The memory contents of the floating point value interpreted as an integer - - - - - Reinterprets the memory contents of a double precision floating point - value as an integer value - - - Double precision floating point value whose memory contents to reinterpret - - - The memory contents of the double precision floating point value - interpreted as an integer - - - - - Reinterprets the memory contents of an integer as a floating point value - - Integer value whose memory contents to reinterpret - - The memory contents of the integer value interpreted as a floating point value - - - - - Reinterprets the memory contents of an integer value as a double precision - floating point value - - Integer whose memory contents to reinterpret - - The memory contents of the integer interpreted as a double precision - floating point value - - - - Union of a floating point variable and an integer - - - The union's value as a floating point variable - - - The union's value as an integer - - - The union's value as an unsigned integer - - - Union of a double precision floating point variable and a long - - - The union's value as a double precision floating point variable - - - The union's value as a long - - - The union's value as an unsigned long - - - - Tests whether a value is greater than the value supplied to its constructor - - - - - The value against which a comparison is to be made - - - - - Initializes a new instance of the class. - - The expected value. - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Tests whether a value is greater than or equal to the value supplied to its constructor - - - - - The value against which a comparison is to be made - - - - - Initializes a new instance of the class. - - The expected value. - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - InstanceOfTypeConstraint is used to test that an object - is of the same type provided or derived from it. - - - - - Construct an InstanceOfTypeConstraint for the type provided - - The expected Type - - - - Test whether an object is of the specified type or a derived type - - The object to be tested - True if the object is of the provided type or derives from it, otherwise false. - - - - Write a description of this constraint to a MessageWriter - - The MessageWriter to use - - - - Tests whether a value is less than the value supplied to its constructor - - - - - The value against which a comparison is to be made - - - - - Initializes a new instance of the class. - - The expected value. - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Tests whether a value is less than or equal to the value supplied to its constructor - - - - - The value against which a comparison is to be made - - - - - Initializes a new instance of the class. - - The expected value. - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Static methods used in creating messages - - - - - Static string used when strings are clipped - - - - - Returns the representation of a type as used in NUnitLite. - This is the same as Type.ToString() except for arrays, - which are displayed with their declared sizes. - - - - - - - Converts any control characters in a string - to their escaped representation. - - The string to be converted - The converted string - - - - Return the a string representation for a set of indices into an array - - Array of indices for which a string is needed - - - - Get an array of indices representing the point in a enumerable, - collection or array corresponding to a single int index into the - collection. - - The collection to which the indices apply - Index in the collection - Array of indices - - - - Clip a string to a given length, starting at a particular offset, returning the clipped - string with ellipses representing the removed parts - - The string to be clipped - The maximum permitted length of the result string - The point at which to start clipping - The clipped string - - - - Clip the expected and actual strings in a coordinated fashion, - so that they may be displayed together. - - - - - - - - - Shows the position two strings start to differ. Comparison - starts at the start index. - - The expected string - The actual string - The index in the strings at which comparison should start - Boolean indicating whether case should be ignored - -1 if no mismatch found, or the index where mismatch found - - - - NaNConstraint tests that the actual value is a double or float NaN - - - - - Test that the actual value is an NaN - - - - - - - Write the constraint description to a specified writer - - - - - - NoItemConstraint applies another constraint to each - item in a collection, failing if any of them succeeds. - - - - - Construct a NoItemConstraint on top of an existing constraint - - - - - - Apply the item constraint to each item in the collection, - failing if any item fails. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - NotConstraint negates the effect of some other constraint - - - - - Initializes a new instance of the class. - - The base constraint to be negated. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for if the base constraint fails, false if it succeeds - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a MessageWriter. - - The writer on which the actual value is displayed - - - - NullConstraint tests that the actual value is null - - - - - Initializes a new instance of the class. - - - - - NullEmptyStringConstraint tests whether a string is either null or empty. - - - - - Constructs a new NullOrEmptyStringConstraint - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - The Numerics class contains common operations on numeric values. - - - - - Checks the type of the object, returning true if - the object is a numeric type. - - The object to check - true if the object is a numeric type - - - - Checks the type of the object, returning true if - the object is a floating point numeric type. - - The object to check - true if the object is a floating point numeric type - - - - Checks the type of the object, returning true if - the object is a fixed point numeric type. - - The object to check - true if the object is a fixed point numeric type - - - - Test two numeric values for equality, performing the usual numeric - conversions and using a provided or default tolerance. If the tolerance - provided is Empty, this method may set it to a default tolerance. - - The expected value - The actual value - A reference to the tolerance in effect - True if the values are equal - - - - Compare two numeric values, performing the usual numeric conversions. - - The expected value - The actual value - The relationship of the values to each other - - - - NUnitComparer encapsulates NUnit's default behavior - in comparing two objects. - - - - - Compares two objects - - - - - - - - Returns the default NUnitComparer. - - - - - Generic version of NUnitComparer - - - - - - Compare two objects of the same type - - - - - NUnitEqualityComparer encapsulates NUnit's handling of - equality tests between objects. - - - - - - - - - - Compares two objects for equality within a tolerance - - The first object to compare - The second object to compare - The tolerance to use in the comparison - - - - - If true, all string comparisons will ignore case - - - - - If true, arrays will be treated as collections, allowing - those of different dimensions to be compared - - - - - Comparison objects used in comparisons for some constraints. - - - - - List of points at which a failure occured. - - - - - RecursionDetector used to check for recursion when - evaluating self-referencing enumerables. - - - - - Compares two objects for equality within a tolerance, setting - the tolerance to the actual tolerance used if an empty - tolerance is supplied. - - - - - Helper method to compare two arrays - - - - - Method to compare two DirectoryInfo objects - - first directory to compare - second directory to compare - true if equivalent, false if not - - - - Returns the default NUnitEqualityComparer - - - - - Gets and sets a flag indicating whether case should - be ignored in determining equality. - - - - - Gets and sets a flag indicating that arrays should be - compared as collections, without regard to their shape. - - - - - Gets the list of external comparers to be used to - test for equality. They are applied to members of - collections, in place of NUnit's own logic. - - - - - Gets the list of failure points for the last Match performed. - The list consists of objects to be interpreted by the caller. - This generally means that the caller may only make use of - objects it has placed on the list at a particular depthy. - - - - - RecursionDetector detects when a comparison - between two enumerables has reached a point - where the same objects that were previously - compared are again being compared. This allows - the caller to stop the comparison if desired. - - - - - Check whether two objects have previously - been compared, returning true if they have. - The two objects are remembered, so that a - second call will always return true. - - - - - OrConstraint succeeds if either member succeeds - - - - - Create an OrConstraint from two other constraints - - The first constraint - The second constraint - - - - Apply the member constraints to an actual value, succeeding - succeeding as soon as one of them succeeds. - - The actual value - True if either constraint succeeded - - - - Write a description for this contraint to a MessageWriter - - The MessageWriter to receive the description - - - - PathConstraint serves as the abstract base of constraints - that operate on paths and provides several helper methods. - - - - - The expected path used in the constraint - - - - - Flag indicating whether a caseInsensitive comparison should be made - - - - - Construct a PathConstraint for a give expected path - - The expected path - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Returns true if the expected path and actual path match - - - - - Returns the string representation of this constraint - - - - - Transform the provided path to its canonical form so that it - may be more easily be compared with other paths. - - The original path - The path in canonical form - - - - Test whether one path in canonical form is under another. - - The first path - supposed to be the parent path - The second path - supposed to be the child path - Indicates whether case should be ignored - - - - - Modifies the current instance to be case-insensitve - and returns it. - - - - - Modifies the current instance to be case-sensitve - and returns it. - - - - - Predicate constraint wraps a Predicate in a constraint, - returning success if the predicate is true. - - - - - Construct a PredicateConstraint from a predicate - - - - - Determines whether the predicate succeeds when applied - to the actual value. - - - - - Writes the description to a MessageWriter - - - - - PropertyConstraint extracts a named property and uses - its value as the actual value for a chained constraint. - - - - - Initializes a new instance of the class. - - The name. - The constraint to apply to the property. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - Returns the string representation of the constraint. - - - - - - PropertyExistsConstraint tests that a named property - exists on the object provided through Match. - - Originally, PropertyConstraint provided this feature - in addition to making optional tests on the vaue - of the property. The two constraints are now separate. - - - - - Initializes a new instance of the class. - - The name of the property. - - - - Test whether the property exists for a given object - - The object to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. - - The writer on which the actual value is displayed - - - - Returns the string representation of the constraint. - - - - - - RangeConstraint tests whether two values are within a - specified range. - - - - - Initializes a new instance of the class. - - From. - To. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - RegexConstraint can test whether a string matches - the pattern provided. - - - - - Initializes a new instance of the class. - - The pattern. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - ResolvableConstraintExpression is used to represent a compound - constraint being constructed at a point where the last operator - may either terminate the expression or may have additional - qualifying constraints added to it. - - It is used, for example, for a Property element or for - an Exception element, either of which may be optionally - followed by constraints that apply to the property or - exception. - - - - - Create a new instance of ResolvableConstraintExpression - - - - - Create a new instance of ResolvableConstraintExpression, - passing in a pre-populated ConstraintBuilder. - - - - - Resolve the current expression to a Constraint - - - - - This operator creates a constraint that is satisfied only if both - argument constraints are satisfied. - - - - - This operator creates a constraint that is satisfied only if both - argument constraints are satisfied. - - - - - This operator creates a constraint that is satisfied only if both - argument constraints are satisfied. - - - - - This operator creates a constraint that is satisfied if either - of the argument constraints is satisfied. - - - - - This operator creates a constraint that is satisfied if either - of the argument constraints is satisfied. - - - - - This operator creates a constraint that is satisfied if either - of the argument constraints is satisfied. - - - - - This operator creates a constraint that is satisfied if the - argument constraint is not satisfied. - - - - - Appends an And Operator to the expression - - - - - Appends an Or operator to the expression. - - - - - ReusableConstraint wraps a constraint expression after - resolving it so that it can be reused consistently. - - - - - Construct a ReusableConstraint from a constraint expression - - The expression to be resolved and reused - - - - Converts a constraint to a ReusableConstraint - - The constraint to be converted - A ReusableConstraint - - - - Returns the string representation of the constraint. - - A string representing the constraint - - - - Resolves the ReusableConstraint by returning the constraint - that it originally wrapped. - - A resolved constraint - - - - SameAsConstraint tests whether an object is identical to - the object passed to its constructor - - - - - Initializes a new instance of the class. - - The expected object. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Summary description for SamePathConstraint. - - - - - Initializes a new instance of the class. - - The expected path - - - - Test whether the constraint is satisfied by a given value - - The expected path - The actual path - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - SamePathOrUnderConstraint tests that one path is under another - - - - - Initializes a new instance of the class. - - The expected path - - - - Test whether the constraint is satisfied by a given value - - The expected path - The actual path - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - SomeItemsConstraint applies another constraint to each - item in a collection, succeeding if any of them succeeds. - - - - - Construct a SomeItemsConstraint on top of an existing constraint - - - - - - Apply the item constraint to each item in the collection, - succeeding if any item succeeds. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - StartsWithConstraint can test whether a string starts - with an expected substring. - - - - - Initializes a new instance of the class. - - The expected string - - - - Test whether the constraint is matched by the actual value. - This is a template method, which calls the IsMatch method - of the derived class. - - - - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - SubPathConstraint tests that the actual path is under the expected path - - - - - Initializes a new instance of the class. - - The expected path - - - - Test whether the constraint is satisfied by a given value - - The expected path - The actual path - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - SubstringConstraint can test whether a string contains - the expected substring. - - - - - Initializes a new instance of the class. - - The expected. - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - ThrowsConstraint is used to test the exception thrown by - a delegate by applying a constraint to it. - - - - - Initializes a new instance of the class, - using a constraint to be applied to the exception. - - A constraint to apply to the caught exception. - - - - Executes the code of the delegate and captures any exception. - If a non-null base constraint was provided, it applies that - constraint to the exception. - - A delegate representing the code to be tested - True if an exception is thrown and the constraint succeeds, otherwise false - - - - Converts an ActualValueDelegate to a TestDelegate - before calling the primary overload. - - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - Returns the string representation of this constraint - - - - - Get the actual exception thrown - used by Assert.Throws. - - - - - ThrowsNothingConstraint tests that a delegate does not - throw an exception. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True if no exception is thrown, otherwise false - - - - Test whether the constraint is satisfied by a given delegate - - Delegate returning the value to be tested - True if no exception is thrown, otherwise false - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. Overridden in ThrowsNothingConstraint to write - information about the exception that was actually caught. - - The writer on which the actual value is displayed - - - - The Tolerance class generalizes the notion of a tolerance - within which an equality test succeeds. Normally, it is - used with numeric types, but it can be used with any - type that supports taking a difference between two - objects and comparing that difference to a value. - - - - - Constructs a linear tolerance of a specdified amount - - - - - Constructs a tolerance given an amount and ToleranceMode - - - - - Tests that the current Tolerance is linear with a - numeric value, throwing an exception if it is not. - - - - - Returns an empty Tolerance object, equivalent to - specifying no tolerance. In most cases, it results - in an exact match but for floats and doubles a - default tolerance may be used. - - - - - Returns a zero Tolerance object, equivalent to - specifying an exact match. - - - - - Gets the ToleranceMode for the current Tolerance - - - - - Gets the value of the current Tolerance instance. - - - - - Returns a new tolerance, using the current amount as a percentage. - - - - - Returns a new tolerance, using the current amount in Ulps. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of days. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of hours. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of minutes. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of seconds. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of milliseconds. - - - - - Returns a new tolerance with a TimeSpan as the amount, using - the current amount as a number of clock ticks. - - - - - Returns true if the current tolerance is empty. - - - - - Modes in which the tolerance value for a comparison can be interpreted. - - - - - The tolerance was created with a value, without specifying - how the value would be used. This is used to prevent setting - the mode more than once and is generally changed to Linear - upon execution of the test. - - - - - The tolerance is used as a numeric range within which - two compared values are considered to be equal. - - - - - Interprets the tolerance as the percentage by which - the two compared values my deviate from each other. - - - - - Compares two values based in their distance in - representable numbers. - - - - - TrueConstraint tests that the actual value is true - - - - - Initializes a new instance of the class. - - - - - UniqueItemsConstraint tests whether all the items in a - collection are unique. - - - - - Check that all items are unique. - - - - - - - Write a description of this constraint to a MessageWriter - - - - - - XmlSerializableConstraint tests whether - an object is serializable in XML format. - - - - - Test whether the constraint is satisfied by a given value - - The value to be tested - True for success, false for failure - - - - Write the constraint description to a MessageWriter - - The writer on which the description is displayed - - - - Write the actual value for a failing constraint test to a - MessageWriter. The default implementation simply writes - the raw value of actual, leaving it to the writer to - perform any formatting. - - The writer on which the actual value is displayed - - - - Returns the string representation of this constraint - - - - - Represents a constraint that succeeds if all the - members of a collection match a base constraint. - - - - - Abstract base for operators that indicate how to - apply a constraint to items in a collection. - - - - - PrefixOperator takes a single constraint and modifies - it's action in some way. - - - - - The ConstraintOperator class is used internally by a - ConstraintBuilder to represent an operator that - modifies or combines constraints. - - Constraint operators use left and right precedence - values to determine whether the top operator on the - stack should be reduced before pushing a new operator. - - - - - The precedence value used when the operator - is about to be pushed to the stack. - - - - - The precedence value used when the operator - is on the top of the stack. - - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - - The syntax element preceding this operator - - - - - The syntax element folowing this operator - - - - - The precedence value used when the operator - is about to be pushed to the stack. - - - - - The precedence value used when the operator - is on the top of the stack. - - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - - Returns the constraint created by applying this - prefix to another constraint. - - - - - - - Constructs a CollectionOperator - - - - - Returns a constraint that will apply the argument - to the members of a collection, succeeding if - they all succeed. - - - - - Operator that requires both it's arguments to succeed - - - - - Abstract base class for all binary operators - - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - - Abstract method that produces a constraint by applying - the operator to its left and right constraint arguments. - - - - - Gets the left precedence of the operator - - - - - Gets the right precedence of the operator - - - - - Construct an AndOperator - - - - - Apply the operator to produce an AndConstraint - - - - - Operator that tests for the presence of a particular attribute - on a type and optionally applies further tests to the attribute. - - - - - Abstract base class for operators that are able to reduce to a - constraint whether or not another syntactic element follows. - - - - - Construct an AttributeOperator for a particular Type - - The Type of attribute tested - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - Represents a constraint that succeeds if the specified - count of members of a collection match a base constraint. - - - - - Construct an ExactCountOperator for a specified count - - The expected count - - - - Returns a constraint that will apply the argument - to the members of a collection, succeeding if - none of them succeed. - - - - - Represents a constraint that succeeds if none of the - members of a collection match a base constraint. - - - - - Returns a constraint that will apply the argument - to the members of a collection, succeeding if - none of them succeed. - - - - - Negates the test of the constraint it wraps. - - - - - Constructs a new NotOperator - - - - - Returns a NotConstraint applied to its argument. - - - - - Operator that requires at least one of it's arguments to succeed - - - - - Construct an OrOperator - - - - - Apply the operator to produce an OrConstraint - - - - - Operator used to test for the presence of a named Property - on an object and optionally apply further tests to the - value of that property. - - - - - Constructs a PropOperator for a particular named property - - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - - Gets the name of the property to which the operator applies - - - - - Represents a constraint that succeeds if any of the - members of a collection match a base constraint. - - - - - Returns a constraint that will apply the argument - to the members of a collection, succeeding if - any of them succeed. - - - - - Operator that tests that an exception is thrown and - optionally applies further tests to the exception. - - - - - Construct a ThrowsOperator - - - - - Reduce produces a constraint from the operator and - any arguments. It takes the arguments from the constraint - stack and pushes the resulting constraint on it. - - - - - Represents a constraint that simply wraps the - constraint provided as an argument, without any - further functionality, but which modifes the - order of evaluation because of its precedence. - - - - - Constructor for the WithOperator - - - - - Returns a constraint that wraps its argument - - - - - Thrown when an assertion failed. - - - - The error message that explains - the reason for the exception - - - The error message that explains - the reason for the exception - The exception that caused the - current exception - - - - Serialization Constructor - - - - - Thrown when an assertion failed. - - - - - - - The error message that explains - the reason for the exception - The exception that caused the - current exception - - - - Serialization Constructor - - - - - Thrown when a test executes inconclusively. - - - - The error message that explains - the reason for the exception - - - The error message that explains - the reason for the exception - The exception that caused the - current exception - - - - Serialization Constructor - - - - - Thrown when an assertion failed. - - - - - - - The error message that explains - the reason for the exception - The exception that caused the - current exception - - - - Serialization Constructor - - - - - - - - - - - Compares two objects of a given Type for equality within a tolerance - - The first object to compare - The second object to compare - The tolerance to use in the comparison - - - - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/license.txt b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/license.txt deleted file mode 100644 index 3b2ad7401fd..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.4/license.txt +++ /dev/null @@ -1,15 +0,0 @@ -Copyright 2002-2014 Charlie Poole -Copyright 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov -Copyright 2000-2002 Philip A. Craig - -This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment (see the following) in the product documentation is required. - -Portions Copyright 2002-2014 Charlie Poole or Copyright 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov or Copyright 2000-2002 Philip A. Craig - -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source distribution. diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config b/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config deleted file mode 100644 index c109c8ad2e5..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/samples/client/petstore/go/README.md b/samples/client/petstore/go/README.md deleted file mode 100644 index 5af32ccefbb..00000000000 --- a/samples/client/petstore/go/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Go API client for swagger - -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. - -## Overview -This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build date: 2016-04-16T15:44:50.329-07:00 -- Build package: class io.swagger.codegen.languages.GoClientCodegen - -## Installation -Put the package under your project folder and add the following in import: -``` - "./swagger" -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*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 -*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **Get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **Get** /pet/{petId} | Find pet by ID -*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **Put** /pet | Update an existing pet -*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **Post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **Post** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **Delete** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **Get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **Get** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **Post** /store/order | Place an order for a pet -*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **Post** /user | Create user -*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **Post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **Post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **Delete** /user/{username} | Delete user -*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **Get** /user/{username} | Get user by user name -*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **Get** /user/login | Logs user into the system -*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **Get** /user/logout | Logs out current logged in user session -*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **Put** /user/{username} | Updated user - - -## Documentation For Models - - - [ApiResponse](docs/ApiResponse.md) - - [Category](docs/Category.md) - - [Order](docs/Order.md) - - [Pet](docs/Pet.md) - - [Tag](docs/Tag.md) - - [User](docs/User.md) - - -## Documentation For Authorization - - -## petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - **write:pets**: modify pets in your account - - **read:pets**: read your pets - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - - -## Author - -apiteam@swagger.io - diff --git a/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore b/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/.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 +# Thsi 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/go/go-petstore/.travis.yml b/samples/client/petstore/go/go-petstore/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/samples/client/petstore/go/go-petstore/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/client/petstore/go/go-petstore/LICENSE b/samples/client/petstore/go/go-petstore/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 9f725fb007b..20083469110 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/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 date: 2016-05-03T10:14:09.589-07:00 +- Build date: 2016-05-25T10:00:28.559-07:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index 100a36da7e1..132ca3949fb 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore import ( @@ -6,7 +28,7 @@ import ( "path/filepath" "reflect" "strings" - + "net/url" "github.com/go-resty/resty" ) @@ -47,7 +69,7 @@ func contains(source []string, containvalue string) bool { func (c *APIClient) CallAPI(path string, method string, postBody interface{}, headerParams map[string]string, - queryParams map[string]string, + queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) (*resty.Response, error) { @@ -79,17 +101,26 @@ func (c *APIClient) CallAPI(path string, method string, return nil, fmt.Errorf("invalid method %v", method) } -func (c *APIClient) ParameterToString(obj interface{}) string { +func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string { if reflect.TypeOf(obj).String() == "[]string" { - return strings.Join(obj.([]string), ",") - } else { - return obj.(string) + switch collectionFormat { + case "pipes": + return strings.Join(obj.([]string), "|") + case "ssv": + return strings.Join(obj.([]string), " ") + case "tsv": + return strings.Join(obj.([]string), "\t") + case "csv" : + return strings.Join(obj.([]string), ",") + } } + + return obj.(string) } func prepareRequest(postBody interface{}, headerParams map[string]string, - queryParams map[string]string, + queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) *resty.Request { @@ -104,7 +135,7 @@ func prepareRequest(postBody interface{}, // add query parameter, if any if len(queryParams) > 0 { - request.SetQueryParams(queryParams) + request.SetMultiValueQueryParams(queryParams) } // add form parameter, if any diff --git a/samples/client/petstore/go/go-petstore/api_response.go b/samples/client/petstore/go/go-petstore/api_response.go index 0404289f96b..57b94271eae 100644 --- a/samples/client/petstore/go/go-petstore/api_response.go +++ b/samples/client/petstore/go/go-petstore/api_response.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore import ( diff --git a/samples/client/petstore/go/go-petstore/category.go b/samples/client/petstore/go/go-petstore/category.go index 197316d62ef..b8591811511 100644 --- a/samples/client/petstore/go/go-petstore/category.go +++ b/samples/client/petstore/go/go-petstore/category.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore type Category struct { diff --git a/samples/client/petstore/go/go-petstore/configuration.go b/samples/client/petstore/go/go-petstore/configuration.go index 5d7df91948e..2bba74c7f53 100644 --- a/samples/client/petstore/go/go-petstore/configuration.go +++ b/samples/client/petstore/go/go-petstore/configuration.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore import ( diff --git a/samples/client/petstore/go/go-petstore/model_api_response.go b/samples/client/petstore/go/go-petstore/model_api_response.go index 774f781ee93..85bba3df10e 100644 --- a/samples/client/petstore/go/go-petstore/model_api_response.go +++ b/samples/client/petstore/go/go-petstore/model_api_response.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore type ModelApiResponse struct { diff --git a/samples/client/petstore/go/go-petstore/order.go b/samples/client/petstore/go/go-petstore/order.go index 582d45a747f..f5b83768175 100644 --- a/samples/client/petstore/go/go-petstore/order.go +++ b/samples/client/petstore/go/go-petstore/order.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore import ( diff --git a/samples/client/petstore/go/go-petstore/pet.go b/samples/client/petstore/go/go-petstore/pet.go index 88e86af7399..b230ea45dac 100644 --- a/samples/client/petstore/go/go-petstore/pet.go +++ b/samples/client/petstore/go/go-petstore/pet.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore type Pet struct { diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index f70ceaa65f0..07dc51eb90e 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -1,9 +1,32 @@ +/* + * 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 + * 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. + */ + package petstore import ( "strings" "fmt" "errors" + "net/url" "os" "io/ioutil" "encoding/json" @@ -48,7 +71,7 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -64,6 +87,7 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } @@ -116,7 +140,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -132,6 +156,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -183,7 +208,7 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -198,8 +223,14 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] } - - queryParams["status"] = a.Configuration.APIClient.ParameterToString(status) + var collectionFormat = "csv" + if collectionFormat == "multi" { + for _, value := range status { + queryParams.Add("status", value) + } + } else { + queryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) + } // to determine the Content-Type header @@ -249,7 +280,7 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -264,8 +295,14 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] } - - queryParams["tags"] = a.Configuration.APIClient.ParameterToString(tags) + var collectionFormat = "csv" + if collectionFormat == "multi" { + for _, value := range tags { + queryParams.Add("tags", value) + } + } else { + queryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) + } // to determine the Content-Type header @@ -316,7 +353,7 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -331,6 +368,7 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -378,7 +416,7 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -394,6 +432,7 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } @@ -447,7 +486,7 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -463,6 +502,7 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/x-www-form-urlencoded", } @@ -516,7 +556,7 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -532,6 +572,7 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ "multipart/form-data", } diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index 56af7223639..e2de74695ee 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -1,9 +1,32 @@ +/* + * 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 + * 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. + */ + package petstore import ( "strings" "fmt" "errors" + "net/url" "encoding/json" ) @@ -47,7 +70,7 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -58,6 +81,7 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -100,7 +124,7 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -115,6 +139,7 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -162,7 +187,7 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -173,6 +198,7 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -220,7 +246,7 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -231,6 +257,7 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } diff --git a/samples/client/petstore/go/go-petstore/tag.go b/samples/client/petstore/go/go-petstore/tag.go index ae901c30ec4..80d219bb36c 100644 --- a/samples/client/petstore/go/go-petstore/tag.go +++ b/samples/client/petstore/go/go-petstore/tag.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore type Tag struct { diff --git a/samples/client/petstore/go/go-petstore/user.go b/samples/client/petstore/go/go-petstore/user.go index 140a94a275b..a2cc5850d75 100644 --- a/samples/client/petstore/go/go-petstore/user.go +++ b/samples/client/petstore/go/go-petstore/user.go @@ -1,3 +1,25 @@ +/* + * 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 + * 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. + */ + package petstore type User struct { diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 1ed8b9a599a..2cd9ed6605c 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -1,9 +1,32 @@ +/* + * 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 + * 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. + */ + package petstore import ( "strings" "fmt" "errors" + "net/url" "encoding/json" ) @@ -46,7 +69,7 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -57,6 +80,7 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -107,7 +131,7 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -118,6 +142,7 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -168,7 +193,7 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -179,6 +204,7 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -230,7 +256,7 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -241,6 +267,7 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -289,7 +316,7 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -300,6 +327,7 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -352,7 +380,7 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -362,11 +390,8 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] } - - queryParams["username"] = a.Configuration.APIClient.ParameterToString(username) - - - queryParams["password"] = a.Configuration.APIClient.ParameterToString(password) + queryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) + queryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) // to determine the Content-Type header @@ -411,7 +436,7 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -422,6 +447,7 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -475,7 +501,7 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { } headerParams := make(map[string]string) - queryParams := make(map[string]string) + queryParams := url.Values{} formParams := make(map[string]string) var postBody interface{} var fileName string @@ -486,6 +512,7 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { headerParams[key] = a.Configuration.DefaultHeader[key] } + // to determine the Content-Type header localVarHttpContentTypes := []string{ } diff --git a/samples/client/petstore/go/pom.xml b/samples/client/petstore/go/pom.xml index 724ac791dcd..7ecbbc7e198 100644 --- a/samples/client/petstore/go/pom.xml +++ b/samples/client/petstore/go/pom.xml @@ -72,4 +72,4 @@ - \ No newline at end of file + diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/default/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/default/.gitignore +++ b/samples/client/petstore/java/default/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/default/.swagger-codegen-ignore b/samples/client/petstore/java/default/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/default/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/default/LICENSE b/samples/client/petstore/java/default/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/default/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Animal.md b/samples/client/petstore/java/default/docs/Animal.md index 3ecb7f991f3..b3f325c3524 100644 --- a/samples/client/petstore/java/default/docs/Animal.md +++ b/samples/client/petstore/java/default/docs/Animal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] diff --git a/samples/client/petstore/java/default/docs/ArrayTest.md b/samples/client/petstore/java/default/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/default/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Cat.md b/samples/client/petstore/java/default/docs/Cat.md index 373af540c41..be6e56fa8ce 100644 --- a/samples/client/petstore/java/default/docs/Cat.md +++ b/samples/client/petstore/java/default/docs/Cat.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/default/docs/Dog.md b/samples/client/petstore/java/default/docs/Dog.md index a1d638d3bad..71a7dbe809e 100644 --- a/samples/client/petstore/java/default/docs/Dog.md +++ b/samples/client/petstore/java/default/docs/Dog.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/default/docs/FakeApi.md index b4e5f34974a..0c1f55a0902 100644 --- a/samples/client/petstore/java/default/docs/FakeApi.md +++ b/samples/client/petstore/java/default/docs/FakeApi.md @@ -32,8 +32,8 @@ Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None byte[] binary = B; // byte[] | None -Date date = new Date(); // Date | None -Date dateTime = new Date(); // Date | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type @@ -70,6 +70,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/default/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/default/docs/FormatTest.md +++ b/samples/client/petstore/java/default/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Name.md b/samples/client/petstore/java/default/docs/Name.md index 5390a15e9cd..ce2fb4dee50 100644 --- a/samples/client/petstore/java/default/docs/Name.md +++ b/samples/client/petstore/java/default/docs/Name.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] diff --git a/samples/client/petstore/java/default/docs/Order.md b/samples/client/petstore/java/default/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/default/docs/Order.md +++ b/samples/client/petstore/java/default/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/default/docs/ReadOnlyFirst.md b/samples/client/petstore/java/default/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/default/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/default/gradlew b/samples/client/petstore/java/default/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/default/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/default/gradlew.bat b/samples/client/petstore/java/default/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/default/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/default/petstore_profiling.output b/samples/client/petstore/java/default/petstore_profiling.output deleted file mode 100644 index 21562548765..00000000000 --- a/samples/client/petstore/java/default/petstore_profiling.output +++ /dev/null @@ -1,23 +0,0 @@ -# To run the profiling: -# mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass="io.swagger.PetstoreProfiling" - -0: ADD PET => 0.987609128 -0: GET PET => 0.450873167 -0: UPDATE PET => 0.447611998 -0: DELETE PET => 0.397707664 -1: ADD PET => 0.395333121 -1: GET PET => 0.381760136 -1: UPDATE PET => 0.395245221 -1: DELETE PET => 0.384854324 -2: ADD PET => 0.400336227 -2: GET PET => 0.378959921 -2: UPDATE PET => 0.397619284 -2: DELETE PET => 0.383307393 -3: ADD PET => 0.385764805 -3: GET PET => 0.40218304 -3: UPDATE PET => 0.387887511 -3: DELETE PET => 0.398063489 -4: ADD PET => 0.384757488 -4: GET PET => 0.398719713 -4: UPDATE PET => 0.383319052 -4: DELETE PET => 0.408516644 diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 2ea4060bc3a..0b24e120100 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -97,8 +97,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 1.7 + 1.7 diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 50c0e8db641..0d7898329d0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T15:55:38.841+08:00") + public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -75,13 +75,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); - authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("test_http_basic", new HttpBasicAuth()); - authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); - authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); + authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 27395e86ba9..600bb507f09 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; @@ -5,65 +30,74 @@ import java.util.List; public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 19b0ebeae4e..cbdadd6262d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index d8d32210b10..4b44c415812 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index 1383dd0decb..03c6c81e434 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java index 40ee5e2774f..18ec9428c16 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,7 +8,8 @@ import io.swagger.client.Configuration; import io.swagger.client.model.*; import io.swagger.client.Pair; -import java.util.Date; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; import java.math.BigDecimal; @@ -54,7 +55,7 @@ public class FakeApi { * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -113,12 +114,12 @@ if (password != null) localVarFormParams.put("password", password); final String[] localVarAccepts = { - "application/xml", "application/json" + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { - + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6882dbc41c0..6ba15566b60 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 64f2c887377..5895370e4d4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 76d2917f24e..8802ebc92c8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..ccaba7709c4 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java index 365f0110b78..25c7d3e421c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java @@ -14,6 +14,7 @@ import io.swagger.annotations.ApiModelProperty; public class Animal { private String className = null; + private String color = "red"; /** @@ -33,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -42,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -56,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..6c1eb23d8d0 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayTest + */ + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java index 21c54aff204..5ef9e23bd96 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java @@ -15,6 +15,7 @@ import io.swagger.client.model.Animal; public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -35,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -62,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -77,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java index ed5581058c6..4b3cc947cc5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java @@ -15,6 +15,7 @@ import io.swagger.client.model.Animal; public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -35,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -62,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -77,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java index c01974880ae..79376150017 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java @@ -6,7 +6,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** @@ -24,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -195,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..2f0972bf41e --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,119 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private String uuid = null; + private DateTime dateTime = null; + private Map map = new HashMap(); + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java index 60b26b55658..1ba2cc5e4a3 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java @@ -17,6 +17,7 @@ public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -60,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -71,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -87,6 +96,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index ed5739592a3..cec651e73a6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; /** @@ -18,7 +18,7 @@ public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -98,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..fdc3587df0e --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java index 47f004c283b..19b55257d0c 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java @@ -111,6 +111,7 @@ public class ApiClientTest { } } + @Ignore("There is no more basic auth in petstore security definitions") @Test public void testSetUsernameAndPassword() { HttpBasicAuth auth = null; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..c564001ad70 --- /dev/null +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,48 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java similarity index 99% rename from samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java index 9e927a69ba2..e75a9c7e7da 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,4 +1,4 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java similarity index 91% rename from samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java index 4b33d380f14..51779f265f0 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,4 +1,4 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; @@ -13,6 +13,8 @@ import java.lang.reflect.Field; import java.util.Map; import java.text.SimpleDateFormat; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -59,6 +61,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -83,7 +86,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java similarity index 98% rename from samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java index 195e5c1e861..c7fb92d2552 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,4 +1,4 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; diff --git a/samples/client/petstore/java/feign/.gitignore b/samples/client/petstore/java/feign/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/feign/.gitignore +++ b/samples/client/petstore/java/feign/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/feign/.swagger-codegen-ignore b/samples/client/petstore/java/feign/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/feign/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/feign/LICENSE b/samples/client/petstore/java/feign/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/feign/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt new file mode 100644 index 00000000000..344d5538317 --- /dev/null +++ b/samples/client/petstore/java/feign/build.sbt @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-feign", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "com.brsanthu" % "migbase64" % "2.2" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/feign/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/feign/gradlew b/samples/client/petstore/java/feign/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/feign/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/feign/gradlew.bat b/samples/client/petstore/java/feign/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/feign/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 164399be4a6..6d055959b5e 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -100,8 +100,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 1.7 + 1.7 @@ -149,19 +149,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 + ${jackson-version} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 303927d064e..75b3a96f2c7 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import feign.Feign; import feign.RequestInterceptor; @@ -18,11 +19,11 @@ import feign.slf4j.Slf4jLogger; import io.swagger.client.auth.*; import io.swagger.client.auth.OAuth.AccessTokenListener; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-17T17:16:23.375+08:00") + public class ApiClient { public interface Api {} - private ObjectMapper objectMapper; + protected ObjectMapper objectMapper; private String basePath = "http://petstore.swagger.io/v2"; private Map apiAuthorizations; private Feign.Builder feignBuilder; @@ -42,16 +43,8 @@ public class ApiClient { RequestInterceptor auth; if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "test_api_client_id") { - auth = new ApiKeyAuth("header", "x-test_api_client_id"); - } else if (authName == "test_api_client_secret") { - auth = new ApiKeyAuth("header", "x-test_api_client_secret"); } else if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "test_api_key_query") { - auth = new ApiKeyAuth("query", "test_api_key_query"); - } else if (authName == "test_api_key_header") { - auth = new ApiKeyAuth("header", "test_api_key_header"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -135,6 +128,13 @@ public class ApiClient { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.registerModule(new JodaModule()); + return objectMapper; + } + + public ObjectMapper getObjectMapper(){ return objectMapper; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 4d348dcd9cb..179a2834da9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 3d1b4a72710..1383dd0decb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index b1dc92805ab..dbabdc64995 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -2,8 +2,9 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -11,13 +12,13 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") + public interface FakeApi extends ApiClient.Api { /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -34,8 +35,8 @@ public interface FakeApi extends ApiClient.Api { */ @RequestLine("POST /fake") @Headers({ - "Content-type: application/x-www-form-urlencoded", - "Accepts: application/json", + "Content-type: application/xml; charset=utf-8", + "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) - void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") Date date, @Param("dateTime") Date dateTime, @Param("password") String password); + void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index e44f445d291..e486495c5a9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public interface PetApi extends ApiClient.Api { @@ -25,7 +25,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("POST /pet") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void addPet(Pet body); @@ -39,7 +39,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("DELETE /pet/{petId}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", "apiKey: {apiKey}" }) void deletePet(@Param("petId") Long petId, @Param("apiKey") String apiKey); @@ -53,7 +53,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("GET /pet/findByStatus?status={status}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) List findPetsByStatus(@Param("status") List status); @@ -66,7 +66,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("GET /pet/findByTags?tags={tags}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) List findPetsByTags(@Param("tags") List tags); @@ -79,7 +79,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("GET /pet/{petId}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) Pet getPetById(@Param("petId") Long petId); @@ -92,7 +92,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("PUT /pet") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void updatePet(Pet body); @@ -107,7 +107,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("POST /pet/{petId}") @Headers({ "Content-type: application/x-www-form-urlencoded", - "Accepts: application/json", + "Accept: application/json", }) void updatePetWithForm(@Param("petId") Long petId, @Param("name") String name, @Param("status") String status); @@ -122,7 +122,7 @@ public interface PetApi extends ApiClient.Api { @RequestLine("POST /pet/{petId}/uploadImage") @Headers({ "Content-type: multipart/form-data", - "Accepts: application/json", + "Accept: application/json", }) ModelApiResponse uploadFile(@Param("petId") Long petId, @Param("additionalMetadata") String additionalMetadata, @Param("file") File file); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 04993aa879a..ee80acba0b4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public interface StoreApi extends ApiClient.Api { @@ -23,7 +23,7 @@ public interface StoreApi extends ApiClient.Api { @RequestLine("DELETE /store/order/{orderId}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void deleteOrder(@Param("orderId") String orderId); @@ -35,7 +35,7 @@ public interface StoreApi extends ApiClient.Api { @RequestLine("GET /store/inventory") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) Map getInventory(); @@ -48,7 +48,7 @@ public interface StoreApi extends ApiClient.Api { @RequestLine("GET /store/order/{orderId}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) Order getOrderById(@Param("orderId") Long orderId); @@ -61,7 +61,7 @@ public interface StoreApi extends ApiClient.Api { @RequestLine("POST /store/order") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) Order placeOrder(Order body); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index 13171d4bed4..6a2c8a6afb1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public interface UserApi extends ApiClient.Api { @@ -23,7 +23,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("POST /user") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void createUser(User body); @@ -36,7 +36,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("POST /user/createWithArray") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void createUsersWithArrayInput(List body); @@ -49,7 +49,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("POST /user/createWithList") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void createUsersWithListInput(List body); @@ -62,7 +62,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("DELETE /user/{username}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void deleteUser(@Param("username") String username); @@ -75,7 +75,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("GET /user/{username}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) User getUserByName(@Param("username") String username); @@ -89,7 +89,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("GET /user/login?username={username}&password={password}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) String loginUser(@Param("username") String username, @Param("password") String password); @@ -101,7 +101,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("GET /user/logout") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void logoutUser(); @@ -115,7 +115,7 @@ public interface UserApi extends ApiClient.Api { @RequestLine("PUT /user/{username}") @Headers({ "Content-type: application/json", - "Accepts: application/json", + "Accept: application/json", }) void updateUser(@Param("username") String username, User body); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java index 5aafbf81a2f..2653474747d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import io.swagger.client.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..ccaba7709c4 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index d6249c18d7e..25c7d3e421c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,10 +10,11 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Animal { private String className = null; + private String color = "red"; /** @@ -32,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -41,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -55,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index f38bf504d50..647e3a893e1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") + public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..6c1eb23d8d0 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayTest + */ + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 278889e60d4..5ef9e23bd96 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -34,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -61,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index f1df969c29c..c6cb703a89e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 1a6374d54bf..4b3cc947cc5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -34,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -61,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 716bfbbc85e..42434e297ff 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 9148bd3d5d5..1c8657fd3ec 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class EnumTest { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 072decf8079..79376150017 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,17 +1,19 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") + public class FormatTest { private Integer integer = null; @@ -23,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -194,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..2f0972bf41e --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,119 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private String uuid = null; + private DateTime dateTime = null; + private Map map = new HashMap(); + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index 4573c22c3da..b2809525c7f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Model200Response { private Integer name = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index eca2b1fb388..32fb86dd323 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 476bf479288..a076d16f964 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class ModelReturn { private Integer _return = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 19ababb8f1c..1ba2cc5e4a3 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,12 +11,13 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -59,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -70,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -86,6 +96,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 359d0105b80..cec651e73a6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,23 +1,24 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -97,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index 511100f868d..da8b76ad024 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -14,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..fdc3587df0e --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 37c5823ed2c..24e57756cb2 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class SpecialModelName { private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index ff51db61fef..9d3bdd8cb9e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 6a4414b5f82..f23553660de 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") + public class User { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..504e027829f --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().buildClient(FakeApi.class); + } + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..2413283e587 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,137 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.Pet; +import io.swagger.client.model.ModelApiResponse; +import java.io.File; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private PetApi api; + + @Before + public void setup() { + api = new ApiClient().buildClient(PetApi.class); + } + + + /** + * Add a new pet to the store + * + * + */ + @Test + public void addPetTest() { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + */ + @Test + public void findPetsByStatusTest() { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + */ + @Test + public void getPetByIdTest() { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + */ + @Test + public void updatePetTest() { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..850109631cf --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,77 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.Order; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private StoreApi api; + + @Before + public void setup() { + api = new ApiClient().buildClient(StoreApi.class); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + @Test + public void deleteOrderTest() { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + */ + @Test + public void getInventoryTest() { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + */ + @Test + public void placeOrderTest() { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..320ef84eb48 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,131 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.User; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private UserApi api; + + @Before + public void setup() { + api = new ApiClient().buildClient(UserApi.class); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + */ + @Test + public void createUserTest() { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + */ + @Test + public void deleteUserTest() { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + */ + @Test + public void getUserByNameTest() { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + */ + @Test + public void logoutUserTest() { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java index ca14be28a80..92a3a951eb5 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -4,13 +4,14 @@ import feign.FeignException; import io.swagger.TestUtils; -import io.swagger.client.*; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; import java.lang.reflect.Field; import java.util.Map; +import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -39,6 +40,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -63,7 +65,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(org.joda.time.DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/jersey2/.gitignore b/samples/client/petstore/java/jersey2/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/jersey2/.gitignore +++ b/samples/client/petstore/java/jersey2/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/jersey2/.swagger-codegen-ignore b/samples/client/petstore/java/jersey2/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/jersey2/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/jersey2/LICENSE b/samples/client/petstore/java/jersey2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 9c98d11c4cd..6574f746d05 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.0" + swagger_annotations_version = "1.5.8" jackson_version = "2.7.0" jersey_version = "2.22.2" jodatime_version = "2.9.3" diff --git a/samples/client/petstore/java/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt new file mode 100644 index 00000000000..08a215edacf --- /dev/null +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -0,0 +1,25 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-jersey2", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", + "joda-time" % "joda-time" % "2.9.3", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/jersey2/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/Animal.md b/samples/client/petstore/java/jersey2/docs/Animal.md index 3ecb7f991f3..b3f325c3524 100644 --- a/samples/client/petstore/java/jersey2/docs/Animal.md +++ b/samples/client/petstore/java/jersey2/docs/Animal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/ArrayTest.md b/samples/client/petstore/java/jersey2/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/Cat.md b/samples/client/petstore/java/jersey2/docs/Cat.md index 373af540c41..be6e56fa8ce 100644 --- a/samples/client/petstore/java/jersey2/docs/Cat.md +++ b/samples/client/petstore/java/jersey2/docs/Cat.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Dog.md b/samples/client/petstore/java/jersey2/docs/Dog.md index a1d638d3bad..71a7dbe809e 100644 --- a/samples/client/petstore/java/jersey2/docs/Dog.md +++ b/samples/client/petstore/java/jersey2/docs/Dog.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index c1fdd310321..0c1f55a0902 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **testEndpointParameters** > testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```java @@ -32,8 +32,8 @@ Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None byte[] binary = B; // byte[] | None -Date date = new Date(); // Date | None -Date dateTime = new Date(); // Date | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type @@ -70,6 +70,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/java/jersey2/docs/FormatTest.md b/samples/client/petstore/java/jersey2/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/jersey2/docs/FormatTest.md +++ b/samples/client/petstore/java/jersey2/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/Name.md b/samples/client/petstore/java/jersey2/docs/Name.md index 5390a15e9cd..ce2fb4dee50 100644 --- a/samples/client/petstore/java/jersey2/docs/Name.md +++ b/samples/client/petstore/java/jersey2/docs/Name.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Order.md b/samples/client/petstore/java/jersey2/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/jersey2/docs/Order.md +++ b/samples/client/petstore/java/jersey2/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey2/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/jersey2/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/jersey2/gradlew b/samples/client/petstore/java/jersey2/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/jersey2/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/jersey2/gradlew.bat b/samples/client/petstore/java/jersey2/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/jersey2/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/jersey2/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index bc43cfe670e..a2607bfd516 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -48,7 +48,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T17:22:31.147+08:00") + public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -84,13 +84,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); - authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("test_http_basic", new HttpBasicAuth()); - authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); - authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); + authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index d5c0fa366bd..600bb507f09 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -1,69 +1,103 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index 91b18d8f79c..cbdadd6262d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index a6ffdc8fbe7..d6f725b2caa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -8,7 +8,7 @@ import java.text.DateFormat; import javax.ws.rs.ext.ContextResolver; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class JSON implements ContextResolver { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index b3532990688..4b44c415812 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 6409e1b1765..03c6c81e434 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index 33c74e7a51c..b8b499c4dee 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -7,15 +7,16 @@ import io.swagger.client.Pair; import javax.ws.rs.core.GenericType; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; import java.math.BigDecimal; -import java.util.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class FakeApi { private ApiClient apiClient; @@ -36,8 +37,8 @@ public class FakeApi { } /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -52,7 +53,7 @@ public class FakeApi { * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -111,12 +112,12 @@ if (password != null) localVarFormParams.put("password", password); final String[] localVarAccepts = { - "application/xml", "application/json" + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { - + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 39b9775f39d..ab85c4ac394 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -16,7 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index d2a87ef01fa..c0c9a166ad7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index b97e2357a4b..7602f4e2ba9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 62506180f53..6ba15566b60 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 65681bc9aa5..5895370e4d4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -9,7 +34,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index dda7cae0a05..8802ebc92c8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") + public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..ccaba7709c4 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 0781e60a4d4..25c7d3e421c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,10 +10,11 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Animal { private String className = null; + private String color = "red"; /** @@ -32,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -41,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -55,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index 04767c63252..647e3a893e1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..6c1eb23d8d0 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayTest + */ + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index 8acadb9a2f6..5ef9e23bd96 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -34,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -61,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index 763fcccf2a7..c6cb703a89e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Category { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index a9e7e2acce0..4b3cc947cc5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -34,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -61,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index 716bfbbc85e..42434e297ff 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 8152b440599..1c8657fd3ec 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class EnumTest { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 4098e37a8a9..79376150017 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,17 +1,19 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class FormatTest { private Integer integer = null; @@ -23,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -194,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..2f0972bf41e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,119 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private String uuid = null; + private DateTime dateTime = null; + private Map map = new HashMap(); + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index 0101cd5e8e3..b2809525c7f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Model200Response { private Integer name = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index af6f23fd782..32fb86dd323 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index 827c22bef67..a076d16f964 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class ModelReturn { private Integer _return = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index b7209d46b19..1ba2cc5e4a3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,12 +11,13 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -59,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -70,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -86,6 +96,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 322b2b832cb..cec651e73a6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,23 +1,24 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -97,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index 07becbd4107..da8b76ad024 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -14,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..fdc3587df0e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index fccd55df94d..24e57756cb2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class SpecialModelName { private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 417f95d4a2f..9d3bdd8cb9e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index bf361b5a765..f23553660de 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") + public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java index 47f004c283b..19b55257d0c 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -111,6 +111,7 @@ public class ApiClientTest { } } + @Ignore("There is no more basic auth in petstore security definitions") @Test public void testSetUsernameAndPassword() { HttpBasicAuth auth = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index f10909ab9e7..9386b3d5236 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -3,10 +3,10 @@ package io.swagger.client; import io.swagger.client.model.Order; import java.lang.Exception; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.TimeZone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import org.junit.*; import static org.junit.Assert.*; @@ -23,26 +23,23 @@ public class JSONTest { @Test public void testDefaultDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime(); final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(dateFormat.parse(dateStr)); + order.setShipDate(dateFormat.parseDateTime(dateStr)); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); + assertEquals(dateStr, dateFormat.print(o.getShipDate())); } @Test public void testCustomDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(dateFormat.parse(dateStr)); + order.setShipDate(dateFormat.parseDateTime(dateStr)); - json.setDateFormat(dateFormat); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); + assertEquals(dateStr, dateFormat.print(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..c564001ad70 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,48 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java similarity index 99% rename from samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java index 51583853257..7f4d27c8b77 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,4 +1,4 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java similarity index 91% rename from samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java index 7ccbdf3f32b..3cc2442c64d 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,9 +1,8 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.*; -import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -11,6 +10,8 @@ import java.lang.reflect.Field; import java.util.Map; import java.text.SimpleDateFormat; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -57,6 +58,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -81,7 +83,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java similarity index 98% rename from samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java index 195e5c1e861..c7fb92d2552 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,4 +1,4 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; diff --git a/samples/client/petstore/java/okhttp-gson/.gitignore b/samples/client/petstore/java/okhttp-gson/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/okhttp-gson/.gitignore +++ b/samples/client/petstore/java/okhttp-gson/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore b/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/okhttp-gson/LICENSE b/samples/client/petstore/java/okhttp-gson/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 57812871f64..d7c6b63ea75 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -98,5 +98,6 @@ dependencies { compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index 1be5d0b6f4d..01a1095f8a4 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -13,6 +13,8 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.6.2", - "junit" % "junit" % "4.12.0" % "test" + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" ) ) diff --git a/samples/client/petstore/java/okhttp-gson/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/Animal.md b/samples/client/petstore/java/okhttp-gson/docs/Animal.md index 3ecb7f991f3..b3f325c3524 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Animal.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Animal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/Cat.md b/samples/client/petstore/java/okhttp-gson/docs/Cat.md index 373af540c41..be6e56fa8ce 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Cat.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Cat.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Dog.md b/samples/client/petstore/java/okhttp-gson/docs/Dog.md index a1d638d3bad..71a7dbe809e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Dog.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Dog.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index c1fdd310321..0c1f55a0902 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **testEndpointParameters** > testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```java @@ -32,8 +32,8 @@ Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None byte[] binary = B; // byte[] | None -Date date = new Date(); // Date | None -Date dateTime = new Date(); // Date | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type @@ -70,6 +70,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/Name.md b/samples/client/petstore/java/okhttp-gson/docs/Name.md index 5390a15e9cd..ce2fb4dee50 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Name.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Name.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Order.md b/samples/client/petstore/java/okhttp-gson/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Order.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/ReadOnlyFirst.md b/samples/client/petstore/java/okhttp-gson/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/okhttp-gson/gradlew b/samples/client/petstore/java/okhttp-gson/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/okhttp-gson/gradlew.bat b/samples/client/petstore/java/okhttp-gson/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson/hello.txt b/samples/client/petstore/java/okhttp-gson/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/okhttp-gson/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 6b5fb468d62..a534184d824 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -104,28 +105,6 @@ 1.7 - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - - @@ -149,6 +128,11 @@ gson ${gson-version} + + joda-time + joda-time + ${jodatime-version} + @@ -159,10 +143,12 @@ - 1.5.8 + 1.5.9 2.7.5 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index fcf2d289fbf..efd0535e654 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.io.IOException; @@ -11,39 +36,39 @@ import java.util.List; * @param The return type */ public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 9328cb74d84..374a185a599 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.Call; @@ -67,1072 +92,1233 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; } - ANDROID_SDK_VERSION = sdkVersion; - } - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; - private Map authentications; + private Map authentications; - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; - private InputStream sslCaCert; - private boolean verifyingSsl; + private InputStream sslCaCert; + private boolean verifyingSsl; - private OkHttpClient httpClient; - private JSON json; + private OkHttpClient httpClient; + private JSON json; - private HttpLoggingInterceptor loggingInterceptor; - - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); + private HttpLoggingInterceptor loggingInterceptor; /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + * Constructor for ApiClient */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); + public ApiClient() { + httpClient = new OkHttpClient(); - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; + verifyingSsl = true; - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); + json = new JSON(this); - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); - public String getBasePath() { - return basePath; - } + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); - public OkHttpClient getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public JSON getJSON() { - return json; - } - - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string. - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - */ - public 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); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; } - if (valueCollection.isEmpty()){ - return params; + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2) + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; } - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; } - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; } - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; } - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; } - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; } - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; } - if (respBody == null || "".equals(respBody)) { - return null; + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; } - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; + public DateFormat getDateFormat() { + return dateFormat; } - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * @see #execute(Call, Type) - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; } - } - /** - * #see executeAsync(Call, Type, ApiCallback) - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param The callback to be executed when the API call finishes - */ - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } - @Override - public void onResponse(Response response) throws IOException { - T result; + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { try { - respBody = response.body().string(); + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public 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); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + throw new ApiException(e); } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + if (respBody == null || "".equals(respBody)) { + return null; } - } - } - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The Content-Type guessed - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). - } else { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); } - } - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } } - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 7c440acc914..600bb507f09 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -1,69 +1,103 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index 0a33f09e64e..b112f15f3e3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.List; @@ -9,38 +34,38 @@ import java.util.Map; * @param T The type of data that is deserialized from response body */ public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; + final private int statusCode; + final private Map> headers; + final private T data; - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } - public int getStatusCode() { - return statusCode; - } + public int getStatusCode() { + return statusCode; + } - public Map> getHeaders() { - return headers; - } + public Map> getHeaders() { + return headers; + } - public T getData() { - return data; - } + public T getData() { + return data; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index 3bb31938c36..cbdadd6262d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index d9d0881a153..7e404e47a26 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.google.gson.Gson; @@ -10,76 +35,118 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + public class JSON { - private ApiClient apiClient; - private Gson gson; + private ApiClient apiClient; + private Gson gson; - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .create(); - } - - public Gson getGson() { - return gson; - } - - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } } - } } class DateAdapter implements JsonSerializer, JsonDeserializer { private final ApiClient apiClient; + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ public DateAdapter(ApiClient apiClient) { super(); this.apiClient = apiClient; } + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { @@ -89,6 +156,16 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { String str = json.getAsJsonPrimitive().getAsString(); @@ -99,3 +176,62 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index ff86c29b167..4b44c415812 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java index 71f34ed1140..a29fc9aec70 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.MediaType; @@ -18,9 +43,9 @@ public class ProgressRequestBody extends RequestBody { } private final RequestBody requestBody; - + private final ProgressRequestListener progressListener; - + private BufferedSink bufferedSink; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { @@ -43,7 +68,7 @@ public class ProgressRequestBody extends RequestBody { if (bufferedSink == null) { bufferedSink = Okio.buffer(sink(sink)); } - + requestBody.writeTo(bufferedSink); bufferedSink.flush(); @@ -51,7 +76,7 @@ public class ProgressRequestBody extends RequestBody { private Sink sink(Sink sink) { return new ForwardingSink(sink) { - + long bytesWritten = 0L; long contentLength = 0L; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java index 138da3f2106..c20672cf0c4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.MediaType; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 67f661726b1..03c6c81e434 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index e021970cdb7..e502060d682 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,14 +36,11 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.lang.reflect.Type; import java.util.ArrayList; @@ -27,196 +49,196 @@ import java.util.List; import java.util.Map; public class FakeApi { - private ApiClient apiClient; + private ApiClient apiClient; - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - private Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + public FakeApi() { + this(Configuration.getDefaultApiClient()); } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + + public ApiClient getApiClient() { + return apiClient; } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); } - }); + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { - Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters (asynchronously) - * Fake endpoint for testing various parameters - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } - Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 75fb730c422..d453504215c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,15 +36,11 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; @@ -28,887 +49,887 @@ import java.util.List; import java.util.Map; public class PetApi { - private ApiClient apiClient; + private ApiClient apiClient; - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public PetApi() { + this(Configuration.getDefaultApiClient()); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public ApiClient getApiClient() { + return apiClient; } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); } - }); + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); } - Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); } - }; + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); } - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); } - Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - List localVarQueryParams = new ArrayList(); + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }); + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); } - Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); } - }; + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index 5d960d0b104..43c530ee964 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,10 +36,6 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.Order; @@ -26,436 +47,436 @@ import java.util.List; import java.util.Map; public class StoreApi { - private ApiClient apiClient; + private ApiClient apiClient; - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public StoreApi() { + this(Configuration.getDefaultApiClient()); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public ApiClient getApiClient() { + return apiClient; } - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); } - }); + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); } - Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index be0269ef28f..9a7054091a3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,10 +36,6 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.User; @@ -26,861 +47,861 @@ import java.util.List; import java.util.Map; public class UserApi { - private ApiClient apiClient; + private ApiClient apiClient; - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + public UserApi() { + this(Configuration.getDefaultApiClient()); } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } - List localVarQueryParams = new ArrayList(); + public ApiClient getApiClient() { + return apiClient; + } - Map localVarHeaderParams = new HashMap(); + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } + List localVarQueryParams = new ArrayList(); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } + List localVarQueryParams = new ArrayList(); - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + Map localVarHeaderParams = new HashMap(); - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; } - - Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); } - }); + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); } - Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Logs out current logged in user session - * - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - List localVarQueryParams = new ArrayList(); + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - Map localVarHeaderParams = new HashMap(); + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }); + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * 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) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * 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) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * 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 callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Updated user + * 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); } - Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } + /** + * Updated user + * 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) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * 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 callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index c4e0be3e711..6ba15566b60 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 6ed16d1db30..9ac184eda83 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -10,32 +35,32 @@ import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index e05568f8f38..8802ebc92c8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:09:59.809+08:00") + public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..da61d03f8d2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,126 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + +/** + * AdditionalPropertiesClass + */ +public class AdditionalPropertiesClass { + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + /** + * Set mapProperty + * + * @param mapProperty mapProperty + */ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Set mapOfMapProperty + * + * @param mapOfMapProperty mapOfMapProperty + */ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index 328f71b7123..dca1f555e38 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,57 +36,88 @@ import com.google.gson.annotations.SerializedName; * Animal */ public class Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); - } - @Override - public int hashCode() { - return Objects.hash(className); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Animal {\n"); - - sb.append(" className: ").append(toIndentedString(className)).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(Object o) { - if (o == null) { - return "null"; + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java index 8be2f1ecd0d..516ff068c08 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,42 +37,44 @@ import com.google.gson.annotations.SerializedName; * AnimalFarm */ public class AnimalFarm extends ArrayList { - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; } - if (o == null || getClass() != o.getClass()) { - return false; + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); } - return true; - } - @Override - public int hashCode() { - return Objects.hash(super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AnimalFarm {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..9795e9b4d79 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,147 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + +/** + * ArrayTest + */ +public class ArrayTest { + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + /** + * Set arrayOfString + * + * @param arrayOfString arrayOfString + */ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Set arrayArrayOfInteger + * + * @param arrayArrayOfInteger arrayArrayOfInteger + */ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Set arrayArrayOfModel + * + * @param arrayArrayOfModel arrayArrayOfModel + */ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java index 9ca89141033..63bef8d8bbf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,73 +37,111 @@ import com.google.gson.annotations.SerializedName; * Cat */ public class Cat extends Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") + private Boolean declawed = null; - @SerializedName("declawed") - private Boolean declawed = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public Boolean getDeclawed() { - return declawed; - } - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + * + * @param declawed declawed + */ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(className, color, declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index f72d42a5746..31e61e56c25 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,72 +36,88 @@ import com.google.gson.annotations.SerializedName; * Category */ public class Category { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("name") + private String name = null; - @SerializedName("name") - private String name = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Category category = (Category) o; - return Objects.equals(this.id, category.id) && + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && Objects.equals(this.name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java index 2fa478001b1..cba351a12c9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,73 +37,111 @@ import com.google.gson.annotations.SerializedName; * Dog */ public class Dog extends Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") + private String breed = null; - @SerializedName("breed") - private String breed = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getBreed() { - return breed; - } - public void setBreed(String breed) { - this.breed = breed; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + /** + * Set breed + * + * @param breed breed + */ + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(className, color, breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java index 6426f26867c..af9ec9f32dc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -9,24 +34,24 @@ import com.google.gson.annotations.SerializedName; * Gets or Sets EnumClass */ public enum EnumClass { - @SerializedName("_abc") - _ABC("_abc"), + @SerializedName("_abc") + _ABC("_abc"), - @SerializedName("-efg") - _EFG("-efg"), + @SerializedName("-efg") + _EFG("-efg"), - @SerializedName("(xyz)") - _XYZ_("(xyz)"); + @SerializedName("(xyz)") + _XYZ_("(xyz)"); - private String value; + private String value; - EnumClass(String value) { - this.value = value; - } + EnumClass(String value) { + this.value = value; + } - @Override - public String toString() { - return String.valueOf(value); - } + @Override + public String toString() { + return String.valueOf(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index 9b3103c16d7..563a785d0b7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,8 +36,6 @@ import com.google.gson.annotations.SerializedName; * EnumTest */ public class EnumTest { - - /** * Gets or Sets enumString */ @@ -35,10 +58,8 @@ public class EnumTest { } } - @SerializedName("enum_string") - private EnumStringEnum enumString = null; - - + @SerializedName("enum_string") + private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ @@ -61,10 +82,8 @@ public class EnumTest { } } - @SerializedName("enum_integer") - private EnumIntegerEnum enumInteger = null; - - + @SerializedName("enum_integer") + private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ @@ -87,80 +106,106 @@ public class EnumTest { } } - @SerializedName("enum_number") - private EnumNumberEnum enumNumber = null; + @SerializedName("enum_number") + private EnumNumberEnum enumNumber = null; - /** - **/ - @ApiModelProperty(value = "") - public EnumStringEnum getEnumString() { - return enumString; - } - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - /** - **/ - @ApiModelProperty(value = "") - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - /** - **/ - @ApiModelProperty(value = "") - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set enumString + * + * @param enumString enumString + */ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; } - EnumTest enumTest = (EnumTest) o; - return Objects.equals(this.enumString, enumTest.enumString) && + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + /** + * Set enumInteger + * + * @param enumInteger enumInteger + */ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + /** + * Set enumNumber + * + * @param enumNumber enumNumber + */ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && Objects.equals(this.enumNumber, enumTest.enumNumber); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).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(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index af3fec2a2ea..66c4203c94e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,10 +1,36 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -13,197 +39,288 @@ import com.google.gson.annotations.SerializedName; * FormatTest */ public class FormatTest { - - @SerializedName("integer") - private Integer integer = null; + @SerializedName("integer") + private Integer integer = null; + @SerializedName("int32") + private Integer int32 = null; + @SerializedName("int64") + private Long int64 = null; + @SerializedName("number") + private BigDecimal number = null; + @SerializedName("float") + private Float _float = null; + @SerializedName("double") + private Double _double = null; + @SerializedName("string") + private String string = null; + @SerializedName("byte") + private byte[] _byte = null; + @SerializedName("binary") + private byte[] binary = null; + @SerializedName("date") + private LocalDate date = null; + @SerializedName("dateTime") + private DateTime dateTime = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("password") + private String password = null; - @SerializedName("int32") - private Integer int32 = null; - - @SerializedName("int64") - private Long int64 = null; - - @SerializedName("number") - private BigDecimal number = null; - - @SerializedName("float") - private Float _float = null; - - @SerializedName("double") - private Double _double = null; - - @SerializedName("string") - private String string = null; - - @SerializedName("byte") - private byte[] _byte = null; - - @SerializedName("binary") - private byte[] binary = null; - - @SerializedName("date") - private Date date = null; - - @SerializedName("dateTime") - private Date dateTime = null; - - @SerializedName("uuid") - private String uuid = null; - - @SerializedName("password") - private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ - @ApiModelProperty(value = "") - public Integer getInteger() { - return integer; - } - public void setInteger(Integer integer) { - this.integer = integer; - } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ - @ApiModelProperty(value = "") - public Integer getInt32() { - return int32; - } - public void setInt32(Integer int32) { - this.int32 = int32; - } - - /** - **/ - @ApiModelProperty(value = "") - public Long getInt64() { - return int64; - } - public void setInt64(Long int64) { - this.int64 = int64; - } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ - @ApiModelProperty(required = true, value = "") - public BigDecimal getNumber() { - return number; - } - public void setNumber(BigDecimal number) { - this.number = number; - } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ - @ApiModelProperty(value = "") - public Float getFloat() { - return _float; - } - public void setFloat(Float _float) { - this._float = _float; - } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ - @ApiModelProperty(value = "") - public Double getDouble() { - return _double; - } - public void setDouble(Double _double) { - this._double = _double; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getString() { - return string; - } - public void setString(String string) { - this.string = string; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public byte[] getByte() { - return _byte; - } - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - /** - **/ - @ApiModelProperty(value = "") - public byte[] getBinary() { - return binary; - } - public void setBinary(byte[] binary) { - this.binary = binary; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public Date getDate() { - return date; - } - public void setDate(Date date) { - this.date = date; - } - - /** - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set integer + * + * @param integer integer + */ + public void setInteger(Integer integer) { + this.integer = integer; } - FormatTest formatTest = (FormatTest) o; - return Objects.equals(this.integer, formatTest.integer) && + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + /** + * Set int32 + * + * @param int32 int32 + */ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + /** + * Set int64 + * + * @param int64 int64 + */ + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + /** + * Set number + * + * @param number number + */ + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + /** + * Set _float + * + * @param _float _float + */ + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + /** + * Set _double + * + * @param _double _double + */ + public void setDouble(Double _double) { + this._double = _double; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + /** + * Set string + * + * @param string string + */ + public void setString(String string) { + this.string = string; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + /** + * Set _byte + * + * @param _byte _byte + */ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + /** + * Set binary + * + * @param binary binary + */ + public void setBinary(byte[] binary) { + this.binary = binary; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + /** + * Set date + * + * @param date date + */ + public void setDate(LocalDate date) { + this.date = date; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + * + * @param dateTime dateTime + */ + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + /** + * Set uuid + * + * @param uuid uuid + */ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + /** + * Set password + * + * @param password password + */ + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && Objects.equals(this.int32, formatTest.int32) && Objects.equals(this.int64, formatTest.int64) && Objects.equals(this.number, formatTest.number) && @@ -216,44 +333,46 @@ public class FormatTest { Objects.equals(this.dateTime, formatTest.dateTime) && Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FormatTest {\n"); - - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..3c88142fc0a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,150 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClass { + @SerializedName("uuid") + private String uuid = null; + @SerializedName("dateTime") + private DateTime dateTime = null; + @SerializedName("map") + private Map map = new HashMap(); + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + /** + * Set uuid + * + * @param uuid uuid + */ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + * + * @param dateTime dateTime + */ + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + /** + * Set map + * + * @param map map + */ + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java index 0ca445cb545..8c7227f3f4e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,57 +37,66 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - - @SerializedName("name") - private Integer name = null; + @SerializedName("name") + private Integer name = null; - /** - **/ - @ApiModelProperty(value = "") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set name + * + * @param name name + */ + public void setName(Integer name) { + this.name = name; } - Model200Response _200Response = (Model200Response) o; - return Objects.equals(this.name, _200Response.name); - } - @Override - public int hashCode() { - return Objects.hash(name); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Model200Response {\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(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\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). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java index da52eda160d..e72fe0c7dbe 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,87 +36,110 @@ import com.google.gson.annotations.SerializedName; * ModelApiResponse */ public class ModelApiResponse { - - @SerializedName("code") - private Integer code = null; + @SerializedName("code") + private Integer code = null; + @SerializedName("type") + private String type = null; + @SerializedName("message") + private String message = null; - @SerializedName("type") - private String type = null; - - @SerializedName("message") - private String message = null; - - /** - **/ - @ApiModelProperty(value = "") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set code + * + * @param code code + */ + public void setCode(Integer code) { + this.code = code; } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(this.code, _apiResponse.code) && + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + /** + * Set type + * + * @param type type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + /** + * Set message + * + * @param message message + */ + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && Objects.equals(this.type, _apiResponse.type) && Objects.equals(this.message, _apiResponse.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelApiResponse {\n"); - - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java index 51aa1f4e055..52fd8ceaca1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,57 +37,66 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - - @SerializedName("return") - private Integer _return = null; + @SerializedName("return") + private Integer _return = null; - /** - **/ - @ApiModelProperty(value = "") - public Integer getReturn() { - return _return; - } - public void setReturn(Integer _return) { - this._return = _return; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set _return + * + * @param _return _return + */ + public void setReturn(Integer _return) { + this._return = _return; } - ModelReturn _return = (ModelReturn) o; - return Objects.equals(this._return, _return._return); - } - @Override - public int hashCode() { - return Objects.hash(_return); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelReturn {\n"); - - sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java index b9cc8170969..fb4ef89df70 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,84 +37,114 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing model name same as property name") public class Name { - - @SerializedName("name") - private Integer name = null; + @SerializedName("name") + private Integer name = null; + @SerializedName("snake_case") + private Integer snakeCase = null; + @SerializedName("property") + private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; - @SerializedName("snake_case") - private Integer snakeCase = null; - - @SerializedName("property") - private String property = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - /** - **/ - @ApiModelProperty(value = "") - public Integer getSnakeCase() { - return snakeCase; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getProperty() { - return property; - } - public void setProperty(String property) { - this.property = property; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set name + * + * @param name name + */ + public void setName(Integer name) { + this.name = name; } - Name name = (Name) o; - return Objects.equals(this.name, name.name) && + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + /** + * Set property + * + * @param property property + */ + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); - } - - @Override - public int hashCode() { - return Objects.hash(name, snakeCase, property); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Name {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); - sb.append(" property: ").append(toIndentedString(property)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index e5c87a21e5b..681715f12ed 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,34 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -12,20 +37,14 @@ import com.google.gson.annotations.SerializedName; * Order */ public class Order { - - @SerializedName("id") - private Long id = null; - - @SerializedName("petId") - private Long petId = null; - - @SerializedName("quantity") - private Integer quantity = null; - - @SerializedName("shipDate") - private Date shipDate = null; - - + @SerializedName("id") + private Long id = null; + @SerializedName("petId") + private Long petId = null; + @SerializedName("quantity") + private Integer quantity = null; + @SerializedName("shipDate") + private DateTime shipDate = null; /** * Order Status */ @@ -51,120 +70,168 @@ public class Order { } } - @SerializedName("status") - private StatusEnum status = null; + @SerializedName("status") + private StatusEnum status = null; + @SerializedName("complete") + private Boolean complete = false; - @SerializedName("complete") - private Boolean complete = false; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - /** - **/ - @ApiModelProperty(value = "") - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - /** - **/ - @ApiModelProperty(value = "") - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - /** - * Order Status - **/ - @ApiModelProperty(value = "Order Status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - /** - **/ - @ApiModelProperty(value = "") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + /** + * Set petId + * + * @param petId petId + */ + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + * + * @param quantity quantity + */ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public DateTime getShipDate() { + return shipDate; + } + + /** + * Set shipDate + * + * @param shipDate shipDate + */ + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + * + * @param status status + */ + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + * + * @param complete complete + */ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && Objects.equals(this.petId, order.petId) && Objects.equals(this.quantity, order.quantity) && Objects.equals(this.shipDate, order.shipDate) && Objects.equals(this.status, order.status) && Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index bc18c39e75f..92c499ae757 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -15,23 +40,16 @@ import com.google.gson.annotations.SerializedName; * Pet */ public class Pet { - - @SerializedName("id") - private Long id = null; - - @SerializedName("category") - private Category category = null; - - @SerializedName("name") - private String name = null; - - @SerializedName("photoUrls") - private List photoUrls = new ArrayList(); - - @SerializedName("tags") - private List tags = new ArrayList(); - - + @SerializedName("id") + private Long id = null; + @SerializedName("category") + private Category category = null; + @SerializedName("name") + private String name = null; + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + @SerializedName("tags") + private List tags = new ArrayList(); /** * pet status in the store */ @@ -57,117 +75,166 @@ public class Pet { } } - @SerializedName("status") - private StatusEnum status = null; + @SerializedName("status") + private StatusEnum status = null; - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - /** - **/ - @ApiModelProperty(value = "") - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - /** - * pet status in the store - **/ - @ApiModelProperty(value = "pet status in the store") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Pet pet = (Pet) o; - return Objects.equals(this.id, pet.id) && + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + /** + * Set category + * + * @param category category + */ + public void setCategory(Category category) { + this.category = category; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + * + * @param photoUrls photoUrls + */ + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + /** + * Set tags + * + * @param tags tags + */ + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + * + * @param status status + */ + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && Objects.equals(this.category, pet.category) && Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && Objects.equals(this.status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..a43413d0903 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,114 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + +/** + * ReadOnlyFirst + */ +public class ReadOnlyFirst { + @SerializedName("bar") + private String bar = null; + @SerializedName("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + /** + * Set baz + * + * @param baz baz + */ + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java index 46cee3c51f8..1ed10e372ae 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,57 +36,66 @@ import com.google.gson.annotations.SerializedName; * SpecialModelName */ public class SpecialModelName { - - @SerializedName("$special[property.name]") - private Long specialPropertyName = null; + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; - /** - **/ - @ApiModelProperty(value = "") - public Long getSpecialPropertyName() { - return specialPropertyName; - } - public void setSpecialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set specialPropertyName + * + * @param specialPropertyName specialPropertyName + */ + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; } - SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); - } - @Override - public int hashCode() { - return Objects.hash(specialPropertyName); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SpecialModelName {\n"); - - sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index 600acee2ba7..a80ef012510 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,72 +36,88 @@ import com.google.gson.annotations.SerializedName; * Tag */ public class Tag { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("name") + private String name = null; - @SerializedName("name") - private String name = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Tag tag = (Tag) o; - return Objects.equals(this.id, tag.id) && + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && Objects.equals(this.name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java index c8b44ce6562..cac9626602d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -1,3 +1,28 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,123 +36,178 @@ import com.google.gson.annotations.SerializedName; * User */ public class User { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("username") + private String username = null; + @SerializedName("firstName") + private String firstName = null; + @SerializedName("lastName") + private String lastName = null; + @SerializedName("email") + private String email = null; + @SerializedName("password") + private String password = null; + @SerializedName("phone") + private String phone = null; + @SerializedName("userStatus") + private Integer userStatus = null; - @SerializedName("username") - private String username = null; - - @SerializedName("firstName") - private String firstName = null; - - @SerializedName("lastName") - private String lastName = null; - - @SerializedName("email") - private String email = null; - - @SerializedName("password") - private String password = null; - - @SerializedName("phone") - private String phone = null; - - @SerializedName("userStatus") - private Integer userStatus = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - /** - * User Status - **/ - @ApiModelProperty(value = "User Status") - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - User user = (User) o; - return Objects.equals(this.id, user.id) && + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + /** + * Set username + * + * @param username username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + * + * @param firstName firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + /** + * Set lastName + * + * @param lastName lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + /** + * Set email + * + * @param email email + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + /** + * Set password + * + * @param password password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + /** + * Set phone + * + * @param phone phone + */ + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + * + * @param userStatus userStatus + */ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && Objects.equals(this.username, user.username) && Objects.equals(this.firstName, user.firstName) && Objects.equals(this.lastName, user.lastName) && @@ -135,39 +215,41 @@ public class User { Objects.equals(this.password, user.password) && Objects.equals(this.phone, user.phone) && Objects.equals(this.userStatus, user.userStatus); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java index fdc2e4c7d4a..8dab64b289e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -6,10 +6,10 @@ import io.swagger.client.model.Order; import java.lang.Exception; import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import org.junit.*; import static org.junit.Assert.*; @@ -27,29 +27,25 @@ public class JSONTest { @Test public void testDefaultDate() throws Exception { - final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC); final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(datetimeFormat.parse(dateStr)); + order.setShipDate(datetimeFormat.parseDateTime(dateStr)); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); Order o = json.deserialize(str, type); - assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + assertEquals(dateStr, datetimeFormat.print(o.getShipDate())); } @Test public void testCustomDate() throws Exception { - final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - datetimeFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(datetimeFormat.parse(dateStr)); + order.setShipDate(datetimeFormat.parseDateTime(dateStr)); - apiClient.setDatetimeFormat(datetimeFormat); - apiClient.setLenientDatetimeFormat(false); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); Order o = json.deserialize(str, type); - assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + assertEquals(dateStr, datetimeFormat.print(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..c564001ad70 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,48 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java similarity index 99% rename from samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java index e378356d0d4..8bfb7605093 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,11 +1,8 @@ -package io.swagger.petstore.test; - -import com.google.gson.reflect.TypeToken; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.*; -import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java similarity index 92% rename from samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java index 0d1910dc1e7..491001cfce3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,10 +1,8 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.ApiException; -import io.swagger.client.*; -import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -12,6 +10,8 @@ import java.lang.reflect.Field; import java.util.Map; import java.text.SimpleDateFormat; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -63,6 +63,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -87,7 +88,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java similarity index 97% rename from samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java index 195e5c1e861..b47a146d737 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,8 +1,7 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; -import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; diff --git a/samples/client/petstore/java/retrofit/.gitignore b/samples/client/petstore/java/retrofit/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/retrofit/.gitignore +++ b/samples/client/petstore/java/retrofit/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/retrofit/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit/LICENSE b/samples/client/petstore/java/retrofit/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index 079d1240a39..401b362d172 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -99,6 +99,7 @@ ext { retrofit_version = "1.9.0" swagger_annotations_version = "1.5.8" junit_version = "4.12" + jodatime_version = "2.9.3" } dependencies { @@ -106,5 +107,6 @@ dependencies { compile "com.squareup.retrofit:retrofit:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit/build.sbt b/samples/client/petstore/java/retrofit/build.sbt new file mode 100644 index 00000000000..629c85c2bf3 --- /dev/null +++ b/samples/client/petstore/java/retrofit/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", + "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/retrofit/gradlew b/samples/client/petstore/java/retrofit/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/retrofit/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/retrofit/gradlew.bat b/samples/client/petstore/java/retrofit/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/retrofit/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit/hello.txt b/samples/client/petstore/java/retrofit/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/retrofit/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 2fe5ddc8efc..ee6ce62988f 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -127,6 +127,11 @@ okhttp ${okhttp-version} + + joda-time + joda-time + ${jodatime-version} + @@ -140,6 +145,7 @@ 1.5.8 1.9.0 2.7.5 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 6540997c319..fe5ad9b37fe 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit.RestAdapter; import retrofit.client.OkClient; @@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -338,3 +347,61 @@ class GsonConverterWrapper implements Converter { } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index fb5b299a706..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:10:49.444+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 89fb9ddba73..02b97c10bf8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -6,8 +6,9 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -16,9 +17,9 @@ import java.util.Map; public interface FakeApi { /** - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Sync method - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -37,11 +38,11 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); /** - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Async method * @param number None (required) * @param _double None (required) @@ -62,6 +63,6 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password, Callback cb + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..a019a4bf886 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,8 +7,8 @@ import retrofit.http.*; import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index 8df24899fb0..9a14a1289fe 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -15,6 +15,9 @@ public class Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + /** **/ @ApiModelProperty(required = true, value = "") @@ -25,6 +28,16 @@ public class Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + @Override public boolean equals(Object o) { @@ -35,12 +48,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className); + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -49,6 +63,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 60a99ed86da..287d6a4d94c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -16,6 +16,9 @@ public class Cat extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") private Boolean declawed = null; @@ -29,6 +32,16 @@ public class Cat extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(className, cat.className) && + Objects.equals(color, cat.color) && Objects.equals(declawed, cat.declawed); } @Override public int hashCode() { - return Objects.hash(className, declawed); + return Objects.hash(className, color, declawed); } @Override @@ -64,6 +78,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 1c31fc93746..5d2ead15f07 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -16,6 +16,9 @@ public class Dog extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") private String breed = null; @@ -29,6 +32,16 @@ public class Dog extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(className, dog.className) && + Objects.equals(color, dog.color) && Objects.equals(breed, dog.breed); } @Override public int hashCode() { - return Objects.hash(className, breed); + return Objects.hash(className, color, breed); } @Override @@ -64,6 +78,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 694335531fd..6063cf33f77 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index b24b87366a4..5aa60a1f6f1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -24,6 +24,9 @@ public class Name { @SerializedName("property") private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; + /** **/ @ApiModelProperty(required = true, value = "") @@ -51,6 +54,13 @@ public class Name { this.property = property; } + /** + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + @Override public boolean equals(Object o) { @@ -63,12 +73,13 @@ public class Name { Name name = (Name) o; return Objects.equals(name, name.name) && Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property); + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -79,6 +90,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..49bc4b90504 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,51 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeApi.class); + } + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // Void response = api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java similarity index 98% rename from samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java index 9fa93650d54..70f8b5aa13f 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,10 +1,9 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.*; import io.swagger.client.CollectionFormats.*; -import io.swagger.client.api.*; import io.swagger.client.model.*; import retrofit.RetrofitError; diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java similarity index 88% rename from samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java index c823245355a..a290fadb847 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,11 +1,12 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.ApiClient; -import io.swagger.client.api.*; import io.swagger.client.model.*; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import retrofit.RetrofitError; import java.lang.reflect.Field; @@ -37,6 +38,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -61,7 +63,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java similarity index 97% rename from samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java index 9b949445cc3..84fae0e990f 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,9 +1,8 @@ -package io.swagger.petstore.test; +package io.swagger.client.api; import io.swagger.TestUtils; import io.swagger.client.ApiClient; -import io.swagger.client.api.*; import io.swagger.client.model.*; diff --git a/samples/client/petstore/java/retrofit2/.gitignore b/samples/client/petstore/java/retrofit2/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/retrofit2/.gitignore +++ b/samples/client/petstore/java/retrofit2/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit2/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2/LICENSE b/samples/client/petstore/java/retrofit2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 6b96656a4a8..4287ae6e53f 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -98,17 +98,16 @@ ext { retrofit_version = "2.0.2" swagger_annotations_version = "1.5.8" junit_version = "4.12" - + jodatime_version = "2.9.3" } dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" - - compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2/build.sbt b/samples/client/petstore/java/retrofit2/build.sbt new file mode 100644 index 00000000000..c42d32f7b53 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/build.sbt @@ -0,0 +1,21 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit2", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Animal.md b/samples/client/petstore/java/retrofit2/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit2/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Cat.md b/samples/client/petstore/java/retrofit2/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Category.md b/samples/client/petstore/java/retrofit2/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Dog.md b/samples/client/petstore/java/retrofit2/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/EnumClass.md b/samples/client/petstore/java/retrofit2/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/retrofit2/docs/EnumTest.md b/samples/client/petstore/java/retrofit2/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md new file mode 100644 index 00000000000..e077fa5c821 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -0,0 +1,76 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + + +# **testEndpointParameters** +> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### 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 + diff --git a/samples/client/petstore/java/retrofit2/docs/FormatTest.md b/samples/client/petstore/java/retrofit2/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Model200Response.md b/samples/client/petstore/java/retrofit2/docs/Model200Response.md new file mode 100644 index 00000000000..0819b88c4f4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Model200Response.md @@ -0,0 +1,10 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit2/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/ModelReturn.md b/samples/client/petstore/java/retrofit2/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Name.md b/samples/client/petstore/java/retrofit2/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Order.md b/samples/client/petstore/java/retrofit2/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Pet.md b/samples/client/petstore/java/retrofit2/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/retrofit2/docs/PetApi.md b/samples/client/petstore/java/retrofit2/docs/PetApi.md new file mode 100644 index 00000000000..40ea199b153 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/PetApi.md @@ -0,0 +1,452 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/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** +> Void addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.addPet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> Void deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + Void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> Void updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.updatePet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> Void updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + Void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit2/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit2/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/StoreApi.md b/samples/client/petstore/java/retrofit2/docs/StoreApi.md new file mode 100644 index 00000000000..30e3c11d440 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/StoreApi.md @@ -0,0 +1,198 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet + + + +# **deleteOrder** +> Void deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + Void result = apiInstance.deleteOrder(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2/docs/Tag.md b/samples/client/petstore/java/retrofit2/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/User.md b/samples/client/petstore/java/retrofit2/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/UserApi.md b/samples/client/petstore/java/retrofit2/docs/UserApi.md new file mode 100644 index 00000000000..b0a0149a50a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/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** +> Void createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + Void result = apiInstance.createUser(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> Void createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithArrayInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> Void createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithListInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> Void deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + Void result = apiInstance.deleteUser(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> Void logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + Void result = apiInstance.logoutUser(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> Void updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + Void result = apiInstance.updateUser(username, body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/retrofit2/gradlew b/samples/client/petstore/java/retrofit2/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/retrofit2/gradlew.bat b/samples/client/petstore/java/retrofit2/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 05774ac3834..26c32613c1f 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -132,6 +132,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + joda-time + joda-time + ${jodatime-version} + @@ -144,8 +149,7 @@ 1.5.8 2.0.2 - - 3.2.0 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index e49bdf24d7b..305b8b783e4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -345,3 +354,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index fe188deeaf5..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:12:35.075+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 28db89beefd..91bd85c1b33 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,9 @@ import retrofit2.http.*; import okhttp3.RequestBody; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -18,8 +19,8 @@ import java.util.Map; public interface FakeApi { /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -38,7 +39,7 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java index d9eed067a88..97145cec55f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,7 @@ package io.swagger.client.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -85,42 +86,55 @@ public class OAuth implements Interceptor { updateAccessToken(null); } - // Build the request - Builder rb = request.newBuilder(); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response.code() == HTTP_UNAUTHORIZED ) { - updateAccessToken(requestAccessToken); - return intercept( chain ); - } - return response; } - public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; } } catch (OAuthSystemException e) { throw new IOException(e); @@ -128,6 +142,7 @@ public class OAuth implements Interceptor { throw new IOException(e); } } + return true; } public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java index 8df24899fb0..9a14a1289fe 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java @@ -15,6 +15,9 @@ public class Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + /** **/ @ApiModelProperty(required = true, value = "") @@ -25,6 +28,16 @@ public class Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + @Override public boolean equals(Object o) { @@ -35,12 +48,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className); + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -49,6 +63,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java index 60a99ed86da..287d6a4d94c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java @@ -16,6 +16,9 @@ public class Cat extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") private Boolean declawed = null; @@ -29,6 +32,16 @@ public class Cat extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(className, cat.className) && + Objects.equals(color, cat.color) && Objects.equals(declawed, cat.declawed); } @Override public int hashCode() { - return Objects.hash(className, declawed); + return Objects.hash(className, color, declawed); } @Override @@ -64,6 +78,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java index 1c31fc93746..5d2ead15f07 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java @@ -16,6 +16,9 @@ public class Dog extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") private String breed = null; @@ -29,6 +32,16 @@ public class Dog extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(className, dog.className) && + Objects.equals(color, dog.color) && Objects.equals(breed, dog.breed); } @Override public int hashCode() { - return Objects.hash(className, breed); + return Objects.hash(className, color, breed); } @Override @@ -64,6 +78,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index 694335531fd..6063cf33f77 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java index b24b87366a4..5aa60a1f6f1 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java @@ -24,6 +24,9 @@ public class Name { @SerializedName("property") private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; + /** **/ @ApiModelProperty(required = true, value = "") @@ -51,6 +54,13 @@ public class Name { this.property = property; } + /** + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + @Override public boolean equals(Object o) { @@ -63,12 +73,13 @@ public class Name { Name name = (Name) o; return Objects.equals(name, name.name) && Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property); + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -79,6 +90,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..bf5a476ab29 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..49bc4b90504 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,51 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeApi.class); + } + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // Void response = api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..8b554674623 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,190 @@ +package io.swagger.client.api; + +import io.swagger.TestUtils; + +import io.swagger.client.ApiClient; +import io.swagger.client.CollectionFormats.*; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; + +import retrofit2.Response; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + Response rp2 = api.addPet(pet).execute(); + + Response rp = api.getPetById(pet.getId()).execute(); + Pet fetched = rp.body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByStatus(new CSVParams("available")).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByTags(new CSVParams("friendly")).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + + api.updatePetWithForm(fetched.getId(), "furt", null).execute(); + Pet updated = api.getPetById(fetched.getId()).execute().body(); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + api.deletePet(fetched.getId(), null).execute(); + + assertFalse(api.getPetById(fetched.getId()).execute().isSuccessful()); + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), null, RequestBody.create(MediaType.parse("text/plain"), file)).execute(); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..4a8fd9a50bd --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,77 @@ +package io.swagger.client.api; + +import io.swagger.TestUtils; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; +import java.util.Map; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; + +import retrofit2.Response; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory().execute().body(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(order.getId()).execute().body(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + Response aa = api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(order.getId()).execute().body(); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())).execute(); + + api.getOrderById(order.getId()).execute(); + //also in retrofit 1 should return an error but don't, check server api impl. + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..70fbb8fef98 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.client.api; + +import io.swagger.TestUtils; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user).execute(); + + User fetched = api.getUserByName(user.getUsername()).execute().body(); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user).execute(); + + String token = api.loginUser(user.getUsername(), user.getPassword()).execute().body(); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser().execute(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/.gitignore b/samples/client/petstore/java/retrofit2rx/.gitignore index 32858aad3c3..7cf39af816c 100644 --- a/samples/client/petstore/java/retrofit2rx/.gitignore +++ b/samples/client/petstore/java/retrofit2rx/.gitignore @@ -8,5 +8,8 @@ *.war *.ear +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* diff --git a/samples/client/petstore/java/retrofit2rx/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2rx/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/.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 +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2rx/LICENSE b/samples/client/petstore/java/retrofit2rx/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle index cbd0119e24b..8d9fa82e69a 100644 --- a/samples/client/petstore/java/retrofit2rx/build.gradle +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -99,7 +99,7 @@ ext { swagger_annotations_version = "1.5.8" junit_version = "4.12" rx_java_version = "1.1.3" - + jodatime_version = "2.9.3" } dependencies { @@ -108,10 +108,9 @@ dependencies { compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" compile "io.reactivex:rxjava:$rx_java_version" - - compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2rx/build.sbt b/samples/client/petstore/java/retrofit2rx/build.sbt new file mode 100644 index 00000000000..3e999d082e0 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/build.sbt @@ -0,0 +1,23 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit2-rx", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile", + "io.reactivex" % "rxjava" % "1.1.3" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Animal.md b/samples/client/petstore/java/retrofit2rx/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit2rx/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Cat.md b/samples/client/petstore/java/retrofit2rx/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Category.md b/samples/client/petstore/java/retrofit2rx/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Dog.md b/samples/client/petstore/java/retrofit2rx/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumClass.md b/samples/client/petstore/java/retrofit2rx/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md new file mode 100644 index 00000000000..e077fa5c821 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -0,0 +1,76 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + + +# **testEndpointParameters** +> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### 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 + diff --git a/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md b/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md new file mode 100644 index 00000000000..0819b88c4f4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md @@ -0,0 +1,10 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit2rx/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/ModelReturn.md b/samples/client/petstore/java/retrofit2rx/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Name.md b/samples/client/petstore/java/retrofit2rx/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Order.md b/samples/client/petstore/java/retrofit2rx/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Pet.md b/samples/client/petstore/java/retrofit2rx/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md new file mode 100644 index 00000000000..40ea199b153 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md @@ -0,0 +1,452 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/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** +> Void addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.addPet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> Void deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + Void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> Void updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.updatePet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> Void updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + Void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2rx/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit2rx/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit2rx/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md new file mode 100644 index 00000000000..30e3c11d440 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md @@ -0,0 +1,198 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet + + + +# **deleteOrder** +> Void deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + Void result = apiInstance.deleteOrder(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Tag.md b/samples/client/petstore/java/retrofit2rx/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/User.md b/samples/client/petstore/java/retrofit2rx/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/UserApi.md b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md new file mode 100644 index 00000000000..b0a0149a50a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/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** +> Void createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + Void result = apiInstance.createUser(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> Void createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithArrayInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> Void createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithListInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> Void deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + Void result = apiInstance.deleteUser(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> Void logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + Void result = apiInstance.logoutUser(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> Void updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + Void result = apiInstance.updateUser(username, body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/retrofit2rx/gradlew b/samples/client/petstore/java/retrofit2rx/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/retrofit2rx/gradlew.bat b/samples/client/petstore/java/retrofit2rx/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index 79d826c3a41..322fd209415 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -132,6 +132,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + joda-time + joda-time + ${jodatime-version} + io.reactivex rxjava @@ -155,7 +160,7 @@ 1.5.8 2.0.2 1.1.3 - 3.2.0 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index 32799fdf3d8..9e424881cbd 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -345,3 +354,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java index ed7083e0370..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T23:45:14.234+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index 768376eb8f9..5e0511922fb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,9 @@ import retrofit2.http.*; import okhttp3.RequestBody; -import java.util.Date; +import org.joda.time.LocalDate; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -18,8 +19,8 @@ import java.util.Map; public interface FakeApi { /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -38,7 +39,7 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 304ea7a29a8..4a2e64b726e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import retrofit2.http.*; import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java index d9eed067a88..97145cec55f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,7 @@ package io.swagger.client.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -85,42 +86,55 @@ public class OAuth implements Interceptor { updateAccessToken(null); } - // Build the request - Builder rb = request.newBuilder(); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.url().toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response.code() == HTTP_UNAUTHORIZED ) { - updateAccessToken(requestAccessToken); - return intercept( chain ); - } - return response; } - public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; } } catch (OAuthSystemException e) { throw new IOException(e); @@ -128,6 +142,7 @@ public class OAuth implements Interceptor { throw new IOException(e); } } + return true; } public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * 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 + * + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java index 8df24899fb0..9a14a1289fe 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java @@ -15,6 +15,9 @@ public class Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + /** **/ @ApiModelProperty(required = true, value = "") @@ -25,6 +28,16 @@ public class Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + @Override public boolean equals(Object o) { @@ -35,12 +48,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className); + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -49,6 +63,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java index 60a99ed86da..287d6a4d94c 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java @@ -16,6 +16,9 @@ public class Cat extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") private Boolean declawed = null; @@ -29,6 +32,16 @@ public class Cat extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(className, cat.className) && + Objects.equals(color, cat.color) && Objects.equals(declawed, cat.declawed); } @Override public int hashCode() { - return Objects.hash(className, declawed); + return Objects.hash(className, color, declawed); } @Override @@ -64,6 +78,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java index 1c31fc93746..5d2ead15f07 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java @@ -16,6 +16,9 @@ public class Dog extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") private String breed = null; @@ -29,6 +32,16 @@ public class Dog extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(className, dog.className) && + Objects.equals(color, dog.color) && Objects.equals(breed, dog.breed); } @Override public int hashCode() { - return Objects.hash(className, breed); + return Objects.hash(className, color, breed); } @Override @@ -64,6 +78,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index 694335531fd..6063cf33f77 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java index b24b87366a4..5aa60a1f6f1 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java @@ -24,6 +24,9 @@ public class Name { @SerializedName("property") private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; + /** **/ @ApiModelProperty(required = true, value = "") @@ -51,6 +54,13 @@ public class Name { this.property = property; } + /** + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + @Override public boolean equals(Object o) { @@ -63,12 +73,13 @@ public class Name { Name name = (Name) o; return Objects.equals(name, name.name) && Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property); + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -79,6 +90,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..49bc4b90504 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,51 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeApi.class); + } + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + Date date = null; + Date dateTime = null; + String password = null; + // Void response = api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..8fa02bed636 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,254 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + @Test + public void testCreateAndGetPet() throws Exception { + final Pet pet = createRandomPet(); + api.addPet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testUpdatePet() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testFindPetsByStatus() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByStatus(new CSVParams("available")).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + }); + + } + }); + + } + + @Test + public void testFindPetsByTags() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByTags(new CSVParams("friendly")).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + }); + + } + }); + + } + + @Test + public void testUpdatePetWithForm() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(final Pet fetched) { + api.updatePetWithForm(fetched.getId(), "furt", null) + .subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet updated) { + assertEquals(updated.getName(), "furt"); + } + }); + + } + }); + } + }); + + + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + + api.deletePet(fetched.getId(), null).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet deletedPet) { + fail("Should not have found deleted pet."); + } + + @Override + public void onError(Throwable e) { + // expected, because the pet has been deleted. + } + }); + } + }); + } + + @Test + public void testUploadFile() throws Exception { + File file = File.createTempFile("test", "hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + + writer.write("Hello world!"); + writer.close(); + + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + RequestBody body = RequestBody.create(MediaType.parse("text/plain"), file); + api.uploadFile(pet.getId(), "a test file", body).subscribe(new SkeletonSubscriber() { + @Override + public void onError(Throwable e) { + // this also yields a 400 for other tests, so I guess it's okay... + } + }); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java new file mode 100644 index 00000000000..47d0df05e28 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java @@ -0,0 +1,30 @@ +package io.swagger.client.api; + +import junit.framework.TestFailure; +import rx.Subscriber; + +/** + * Skeleton subscriber for tests that will fail when onError() is called unexpectedly. + */ +public abstract class SkeletonSubscriber extends Subscriber { + + public static SkeletonSubscriber failTestOnError() { + return new SkeletonSubscriber() { + }; + } + + @Override + public void onCompleted() { + // space for rent + } + + @Override + public void onNext(T t) { + // space for rent + } + + @Override + public void onError(Throwable e) { + throw new RuntimeException("Subscriber onError() called with unhandled exception!", e); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..62f1b194766 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; +import java.util.Map; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; + +import retrofit2.Response; + +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + api.getInventory().subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(Map inventory) { + assertTrue(inventory.keySet().size() > 0); + } + }); + + } + + @Test + public void testPlaceOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(order.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + }); + } + + @Test + public void testDeleteOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getOrderById(order.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(fetched.getId(), order.getId()); + } + }); + + + api.deleteOrder(String.valueOf(order.getId())).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(order.getId()) + .subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order order) { + throw new RuntimeException("Should not have found deleted order."); + } + + @Override + public void onError(Throwable e) { + // should not find deleted order. + } + } + ); + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, System.currentTimeMillis()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..02c3942b210 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,107 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.*; + + +import java.util.Arrays; + +import org.junit.*; + +import static org.junit.Assert.*; + +/** + * NOTE: This serves as a sample and test case for the generator, which is why this is java-7 code. + * Much looks much nicer with no anonymous classes. + */ +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + final User user = createUser(); + + api.createUser(user).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getUserByName(user.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user.getId(), fetched.getId()); + } + }); + } + }); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testCreateUsersWithList() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + api.loginUser(user.getUsername(), user.getPassword()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(String token) { + assertTrue(token.startsWith("logged in user session:")); + } + }); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} \ No newline at end of file diff --git a/samples/client/petstore/javascript/.swagger-codegen-ignore b/samples/client/petstore/javascript/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/javascript/.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 +# Thsi 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/javascript/LICENSE b/samples/client/petstore/javascript/LICENSE new file mode 100644 index 00000000000..d9a10c0d8e8 --- /dev/null +++ b/samples/client/petstore/javascript/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 1bf60abb9c3..dfc15cba3f9 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -1,12 +1,12 @@ # swagger-petstore SwaggerPetstore - JavaScript client for swagger-petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +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 SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-06T18:34:50.267+08:00 +- Build date: 2016-05-29T20:52:27.873+08:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -91,7 +91,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +*SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *SwaggerPetstore.PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *SwaggerPetstore.PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -116,20 +116,24 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [SwaggerPetstore.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [SwaggerPetstore.Animal](docs/Animal.md) - [SwaggerPetstore.AnimalFarm](docs/AnimalFarm.md) - [SwaggerPetstore.ApiResponse](docs/ApiResponse.md) + - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) - [SwaggerPetstore.Dog](docs/Dog.md) - [SwaggerPetstore.EnumClass](docs/EnumClass.md) - [SwaggerPetstore.EnumTest](docs/EnumTest.md) - [SwaggerPetstore.FormatTest](docs/FormatTest.md) + - [SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [SwaggerPetstore.Model200Response](docs/Model200Response.md) - [SwaggerPetstore.ModelReturn](docs/ModelReturn.md) - [SwaggerPetstore.Name](docs/Name.md) - [SwaggerPetstore.Order](docs/Order.md) - [SwaggerPetstore.Pet](docs/Pet.md) + - [SwaggerPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) - [SwaggerPetstore.Tag](docs/Tag.md) - [SwaggerPetstore.User](docs/User.md) @@ -138,6 +142,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -147,9 +157,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/javascript/docs/AdditionalPropertiesClass.md b/samples/client/petstore/javascript/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..f25c4fceec7 --- /dev/null +++ b/samples/client/petstore/javascript/docs/AdditionalPropertiesClass.md @@ -0,0 +1,7 @@ +# SwaggerPetstore.AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript/docs/Animal.md b/samples/client/petstore/javascript/docs/Animal.md index c37d95695a0..3ae52d9db17 100644 --- a/samples/client/petstore/javascript/docs/Animal.md +++ b/samples/client/petstore/javascript/docs/Animal.md @@ -4,5 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] [default to 'red'] diff --git a/samples/client/petstore/javascript/docs/ArrayTest.md b/samples/client/petstore/javascript/docs/ArrayTest.md new file mode 100644 index 00000000000..2e056172023 --- /dev/null +++ b/samples/client/petstore/javascript/docs/ArrayTest.md @@ -0,0 +1,7 @@ +# SwaggerPetstore.ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index 121056d1c56..6eba9c1b023 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **testEndpointParameters** > testEndpointParameters(_number, _double, _string, _byte, opts) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```javascript @@ -77,6 +77,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/javascript/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/javascript/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..cecc4a1156a --- /dev/null +++ b/samples/client/petstore/javascript/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | **Date** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Name.md b/samples/client/petstore/javascript/docs/Name.md index 3bdb76be085..6c47d402743 100644 --- a/samples/client/petstore/javascript/docs/Name.md +++ b/samples/client/petstore/javascript/docs/Name.md @@ -6,5 +6,6 @@ Name | Type | Description | Notes **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] diff --git a/samples/client/petstore/javascript/docs/ReadOnlyFirst.md b/samples/client/petstore/javascript/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..5a16f8acce0 --- /dev/null +++ b/samples/client/petstore/javascript/docs/ReadOnlyFirst.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/package.json b/samples/client/petstore/javascript/package.json index 8ff02a78ae3..53ea2d8faf9 100644 --- a/samples/client/petstore/javascript/package.json +++ b/samples/client/petstore/javascript/package.json @@ -1,8 +1,8 @@ { "name": "swagger-petstore", "version": "1.0.0", - "description": "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.", - "license": "Apache 2.0", + "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: \" \\ ", + "license": "Apache-2.0", "main": "src/index.js", "scripts": { "test": "./node_modules/mocha/bin/mocha --recursive" diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 2598dd8d9ea..d45704dcdac 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -40,8 +40,8 @@ * @type {Array.} */ this.authentications = { - 'petstore_auth': {type: 'oauth2'}, - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'} + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'petstore_auth': {type: 'oauth2'} }; /** * The default HTTP headers to be included for all API calls. diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index f75b8f55890..9db45d334f5 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -41,8 +41,8 @@ */ /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param {Number} _number None * @param {Number} _double None * @param {String} _string None @@ -105,8 +105,8 @@ }; var authNames = []; - var contentTypes = []; - var accepts = ['application/xml', 'application/json']; + var contentTypes = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; + var accepts = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; var returnType = null; return this.apiClient.callApi( diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 727b4782f45..2c3e34b4efd 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -1,16 +1,16 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/Order', 'model/Pet', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, Animal, AnimalFarm, ApiResponse, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayTest, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose..
+ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ .
* The index module provides access to constructors for all the classes which comprise the public API. *

* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: @@ -46,6 +46,11 @@ * @property {module:ApiClient} */ ApiClient: ApiClient, + /** + * The AdditionalPropertiesClass model constructor. + * @property {module:model/AdditionalPropertiesClass} + */ + AdditionalPropertiesClass: AdditionalPropertiesClass, /** * The Animal model constructor. * @property {module:model/Animal} @@ -61,6 +66,11 @@ * @property {module:model/ApiResponse} */ ApiResponse: ApiResponse, + /** + * The ArrayTest model constructor. + * @property {module:model/ArrayTest} + */ + ArrayTest: ArrayTest, /** * The Cat model constructor. * @property {module:model/Cat} @@ -91,6 +101,11 @@ * @property {module:model/FormatTest} */ FormatTest: FormatTest, + /** + * The MixedPropertiesAndAdditionalPropertiesClass model constructor. + * @property {module:model/MixedPropertiesAndAdditionalPropertiesClass} + */ + MixedPropertiesAndAdditionalPropertiesClass: MixedPropertiesAndAdditionalPropertiesClass, /** * The Model200Response model constructor. * @property {module:model/Model200Response} @@ -116,6 +131,11 @@ * @property {module:model/Pet} */ Pet: Pet, + /** + * The ReadOnlyFirst model constructor. + * @property {module:model/ReadOnlyFirst} + */ + ReadOnlyFirst: ReadOnlyFirst, /** * The SpecialModelName model constructor. * @property {module:model/SpecialModelName} diff --git a/samples/client/petstore/javascript/src/model/AdditionalPropertiesClass.js b/samples/client/petstore/javascript/src/model/AdditionalPropertiesClass.js new file mode 100644 index 00000000000..8dd4d1c9795 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/AdditionalPropertiesClass.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.AdditionalPropertiesClass = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The AdditionalPropertiesClass model module. + * @module model/AdditionalPropertiesClass + * @version 1.0.0 + */ + + /** + * Constructs a new AdditionalPropertiesClass. + * @alias module:model/AdditionalPropertiesClass + * @class + * @extends Object + */ + var exports = function() { + var _this = this; + + return _this; + }; + + /** + * Constructs a AdditionalPropertiesClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/AdditionalPropertiesClass} obj Optional instance to populate. + * @return {module:model/AdditionalPropertiesClass} The populated AdditionalPropertiesClass instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + ApiClient.constructFromObject(data, obj, String); + + } + return obj; + } + + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/Animal.js b/samples/client/petstore/javascript/src/model/Animal.js index e42874c669b..28e5904e840 100644 --- a/samples/client/petstore/javascript/src/model/Animal.js +++ b/samples/client/petstore/javascript/src/model/Animal.js @@ -34,6 +34,7 @@ var _this = this; _this['className'] = className; + }; /** @@ -50,6 +51,9 @@ if (data.hasOwnProperty('className')) { obj['className'] = ApiClient.convertToType(data['className'], 'String'); } + if (data.hasOwnProperty('color')) { + obj['color'] = ApiClient.convertToType(data['color'], 'String'); + } } return obj; } @@ -58,6 +62,11 @@ * @member {String} className */ exports.prototype['className'] = undefined; + /** + * @member {String} color + * @default 'red' + */ + exports.prototype['color'] = 'red'; diff --git a/samples/client/petstore/javascript/src/model/ArrayTest.js b/samples/client/petstore/javascript/src/model/ArrayTest.js new file mode 100644 index 00000000000..5a11c6a47bf --- /dev/null +++ b/samples/client/petstore/javascript/src/model/ArrayTest.js @@ -0,0 +1,59 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ArrayTest = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The ArrayTest model module. + * @module model/ArrayTest + * @version 1.0.0 + */ + + /** + * Constructs a new ArrayTest. + * @alias module:model/ArrayTest + * @class + */ + var exports = function() { + var _this = this; + + }; + + /** + * Constructs a ArrayTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ArrayTest} obj Optional instance to populate. + * @return {module:model/ArrayTest} The populated ArrayTest instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + } + return obj; + } + + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/MixedPropertiesAndAdditionalPropertiesClass.js b/samples/client/petstore/javascript/src/model/MixedPropertiesAndAdditionalPropertiesClass.js new file mode 100644 index 00000000000..1d51ce6c3f8 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/MixedPropertiesAndAdditionalPropertiesClass.js @@ -0,0 +1,78 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + + + + /** + * The MixedPropertiesAndAdditionalPropertiesClass model module. + * @module model/MixedPropertiesAndAdditionalPropertiesClass + * @version 1.0.0 + */ + + /** + * Constructs a new MixedPropertiesAndAdditionalPropertiesClass. + * @alias module:model/MixedPropertiesAndAdditionalPropertiesClass + * @class + * @extends Object + */ + var exports = function() { + var _this = this; + + + + return _this; + }; + + /** + * Constructs a MixedPropertiesAndAdditionalPropertiesClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/MixedPropertiesAndAdditionalPropertiesClass} obj Optional instance to populate. + * @return {module:model/MixedPropertiesAndAdditionalPropertiesClass} The populated MixedPropertiesAndAdditionalPropertiesClass instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + ApiClient.constructFromObject(data, obj, Animal); + + if (data.hasOwnProperty('uuid')) { + obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); + } + if (data.hasOwnProperty('dateTime')) { + obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); + } + } + return obj; + } + + /** + * @member {String} uuid + */ + exports.prototype['uuid'] = undefined; + /** + * @member {Date} dateTime + */ + exports.prototype['dateTime'] = undefined; + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/Name.js b/samples/client/petstore/javascript/src/model/Name.js index 93d1d55deb2..f8c24ef770c 100644 --- a/samples/client/petstore/javascript/src/model/Name.js +++ b/samples/client/petstore/javascript/src/model/Name.js @@ -37,6 +37,7 @@ _this['name'] = name; + }; /** @@ -59,6 +60,9 @@ if (data.hasOwnProperty('property')) { obj['property'] = ApiClient.convertToType(data['property'], 'String'); } + if (data.hasOwnProperty('123Number')) { + obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Integer'); + } } return obj; } @@ -75,6 +79,10 @@ * @member {String} property */ exports.prototype['property'] = undefined; + /** + * @member {Integer} 123Number + */ + exports.prototype['123Number'] = undefined; diff --git a/samples/client/petstore/javascript/src/model/ReadOnlyFirst.js b/samples/client/petstore/javascript/src/model/ReadOnlyFirst.js new file mode 100644 index 00000000000..394af906e73 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/ReadOnlyFirst.js @@ -0,0 +1,75 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ReadOnlyFirst = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The ReadOnlyFirst model module. + * @module model/ReadOnlyFirst + * @version 1.0.0 + */ + + /** + * Constructs a new ReadOnlyFirst. + * @alias module:model/ReadOnlyFirst + * @class + */ + var exports = function() { + var _this = this; + + + + }; + + /** + * Constructs a ReadOnlyFirst from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ReadOnlyFirst} obj Optional instance to populate. + * @return {module:model/ReadOnlyFirst} The populated ReadOnlyFirst instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('bar')) { + obj['bar'] = ApiClient.convertToType(data['bar'], 'String'); + } + if (data.hasOwnProperty('baz')) { + obj['baz'] = ApiClient.convertToType(data['baz'], 'String'); + } + } + return obj; + } + + /** + * @member {String} bar + */ + exports.prototype['bar'] = undefined; + /** + * @member {String} baz + */ + exports.prototype['baz'] = undefined; + + + + + return exports; +})); + + diff --git a/samples/client/petstore/objc/.swagger-codegen-ignore b/samples/client/petstore/objc/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/objc/.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 +# Thsi 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/objc/LICENSE b/samples/client/petstore/objc/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/objc/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index f4b3f2f2f76..44bff87c42e 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-08T12:06:01.121+02:00 +- Build date: 2016-05-27T16:03:28.462+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -37,6 +37,7 @@ pod 'SwaggerClient', :path => 'Vendor/SwaggerClient' ### Usage Import the following: + ```objc #import #import @@ -71,23 +72,15 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to the store (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; // Add a new pet to the store - [apiInstance addPetWithBody:body +[apiInstance addPetWithBody:body completionHandler: ^(NSError* error)) { if (error) { NSLog(@"Error: %@", error); } }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->addPet: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} ``` diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 740680eb9e2..eab61d4dc32 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,24 +13,25 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + 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 DESC s.platform = :ios, '7.0' s.requires_arc = true - s.framework = 'SystemConfiguration' - + s.frameworks = 'SystemConfiguration', 'CoreData' + s.homepage = "https://github.com/swagger-api/swagger-codegen" - s.license = "MIT" + s.license = "Apache License, Version 2.0" s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } s.author = { "Swagger" => "apiteam@swagger.io" } - s.source_files = 'SwaggerClient/**/*' + s.source_files = 'SwaggerClient/**/*.{m,h}' s.public_header_files = 'SwaggerClient/**/*.h' + s.resources = 'SwaggerClient/**/*.{xcdatamodeld,xcdatamodel}' - s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h similarity index 59% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h index 908771588e0..97f914a627e 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h @@ -1,45 +1,58 @@ #import #import "SWGPet.h" -#import "SWGObject.h" -#import "SWGApiClient.h" - +#import "SWGApi.h" /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ -@interface SWGPetApi: NSObject -@property(nonatomic, assign)SWGApiClient *apiClient; +@interface SWGPetApi: NSObject + +extern NSString* kSWGPetApiErrorDomain; +extern NSInteger kSWGPetApiMissingParamErrorCode; + ++(instancetype) sharedAPI; --(instancetype) initWithApiClient:(SWGApiClient *)apiClient; --(void) addHeader:(NSString*)value forKey:(NSString*)key; --(unsigned long) requestQueueSize; -+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(SWGPetApi*) sharedAPI; -/// -/// /// Add a new pet to the store /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) /// +/// code:400 message:"Invalid pet value" /// /// @return -(NSNumber*) deletePetWithPetId: (NSNumber*) petId @@ -47,60 +60,60 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Finds Pets by status /// Multiple status values can be provided with comma seperated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid status value" /// /// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Finds Pets by tags /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid tag value" /// /// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found" /// /// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; -/// -/// /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found", +/// code:405 message:"Validation exception" /// /// @return -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Updates a pet in the store with form data /// /// @@ -108,6 +121,7 @@ /// @param name Updated name of the pet (optional) /// @param status Updated status of the pet (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId @@ -116,8 +130,6 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// uploads an image /// /// @@ -125,6 +137,7 @@ /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m similarity index 64% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m index b3ebc31bf68..409f5b86655 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m @@ -4,24 +4,29 @@ @interface SWGPetApi () - @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; + +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; + @end @implementation SWGPetApi -static SWGPetApi* singletonAPI = nil; +NSString* kSWGPetApiErrorDomain = @"SWGPetApiErrorDomain"; +NSInteger kSWGPetApiMissingParamErrorCode = 234513; + +@synthesize apiClient = _apiClient; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; if (config.apiClient == nil) { config.apiClient = [[SWGApiClient alloc] init]; } - self.apiClient = config.apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } @@ -29,39 +34,36 @@ static SWGPetApi* singletonAPI = nil; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - self.apiClient = apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { - singletonAPI = [[SWGPetApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; ++ (instancetype)sharedAPI { + static SWGPetApi *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; } -+(SWGPetApi*) sharedAPI { - if (singletonAPI == nil) { - singletonAPI = [[SWGPetApi alloc] init]; - } - return singletonAPI; +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; } -(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - --(unsigned long) requestQueueSize { +-(NSUInteger) requestQueueSize { return [SWGApiClient requestQueueSize]; } @@ -79,31 +81,24 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -126,7 +121,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -145,15 +142,19 @@ static SWGPetApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `deletePet`"]; + NSParameterAssert(petId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"petId"] }; + NSError* error = [NSError errorWithDomain:kSWGPetApiErrorDomain code:kSWGPetApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -161,29 +162,22 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; if (apiKey != nil) { headerParams[@"api_key"] = apiKey; } - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -205,7 +199,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -222,9 +218,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -233,24 +227,19 @@ static SWGPetApi* singletonAPI = nil; queryParams[@"status"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: status format: @"multi"]; } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -272,7 +261,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"NSArray*" completionBlock: ^(id data, NSError *error) { - handler((NSArray*)data, error); + if(handler) { + handler((NSArray*)data, error); + } } ]; } @@ -289,9 +280,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -300,24 +289,19 @@ static SWGPetApi* singletonAPI = nil; queryParams[@"tags"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: tags format: @"multi"]; } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -339,7 +323,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"NSArray*" completionBlock: ^(id data, NSError *error) { - handler((NSArray*)data, error); + if(handler) { + handler((NSArray*)data, error); + } } ]; } @@ -355,15 +341,19 @@ static SWGPetApi* singletonAPI = nil; completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `getPetById`"]; + NSParameterAssert(petId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"petId"] }; + NSError* error = [NSError errorWithDomain:kSWGPetApiErrorDomain code:kSWGPetApiMissingParamErrorCode userInfo:userInfo]; + handler(nil, error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -371,24 +361,19 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth", @"api_key"]; @@ -410,7 +395,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"SWGPet*" completionBlock: ^(id data, NSError *error) { - handler((SWGPet*)data, error); + if(handler) { + handler((SWGPet*)data, error); + } } ]; } @@ -427,31 +414,24 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -474,7 +454,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -496,15 +478,19 @@ static SWGPetApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `updatePetWithForm`"]; + NSParameterAssert(petId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"petId"] }; + NSError* error = [NSError errorWithDomain:kSWGPetApiErrorDomain code:kSWGPetApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -512,24 +498,19 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -557,7 +538,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -579,15 +562,19 @@ static SWGPetApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `uploadFile`"]; + NSParameterAssert(petId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"petId"] }; + NSError* error = [NSError errorWithDomain:kSWGPetApiErrorDomain code:kSWGPetApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}/uploadImage"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -595,24 +582,19 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"multipart/form-data"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -638,7 +620,9 @@ static SWGPetApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } diff --git a/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h new file mode 100644 index 00000000000..bbd588dba25 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h @@ -0,0 +1,89 @@ +#import +#import "SWGOrder.h" +#import "SWGApi.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + +@interface SWGStoreApi: NSObject + +extern NSString* kSWGStoreApiErrorDomain; +extern NSInteger kSWGStoreApiMissingParamErrorCode; + ++(instancetype) sharedAPI; + +/// 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 +/// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" +/// +/// @return +-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId + completionHandler: (void (^)(NSError* error)) handler; + + +/// Returns pet inventories by status +/// Returns a map of status codes to quantities +/// +/// +/// code:200 message:"successful operation" +/// +/// @return NSDictionary* +-(NSNumber*) getInventoryWithCompletionHandler: + (void (^)(NSDictionary* output, NSError* error)) handler; + + +/// 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 +/// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" +/// +/// @return SWGOrder* +-(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId + completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + + +/// Place an order for a pet +/// +/// +/// @param body order placed for purchasing the pet (optional) +/// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid Order" +/// +/// @return SWGOrder* +-(NSNumber*) placeOrderWithBody: (SWGOrder*) body + completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + + + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m similarity index 62% rename from samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m index 336258c3c5b..e5964200f20 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m @@ -4,24 +4,29 @@ @interface SWGStoreApi () - @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; + +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; + @end @implementation SWGStoreApi -static SWGStoreApi* singletonAPI = nil; +NSString* kSWGStoreApiErrorDomain = @"SWGStoreApiErrorDomain"; +NSInteger kSWGStoreApiMissingParamErrorCode = 234513; + +@synthesize apiClient = _apiClient; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; if (config.apiClient == nil) { config.apiClient = [[SWGApiClient alloc] init]; } - self.apiClient = config.apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } @@ -29,39 +34,36 @@ static SWGStoreApi* singletonAPI = nil; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - self.apiClient = apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { - singletonAPI = [[SWGStoreApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; ++ (instancetype)sharedAPI { + static SWGStoreApi *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; } -+(SWGStoreApi*) sharedAPI { - if (singletonAPI == nil) { - singletonAPI = [[SWGStoreApi alloc] init]; - } - return singletonAPI; +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; } -(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - --(unsigned long) requestQueueSize { +-(NSUInteger) requestQueueSize { return [SWGApiClient requestQueueSize]; } @@ -78,15 +80,19 @@ static SWGStoreApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `orderId` when calling `deleteOrder`"]; + NSParameterAssert(orderId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"orderId"] }; + NSError* error = [NSError errorWithDomain:kSWGStoreApiErrorDomain code:kSWGStoreApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -94,24 +100,19 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -133,7 +134,9 @@ static SWGStoreApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -148,31 +151,24 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"api_key"]; @@ -194,7 +190,9 @@ static SWGStoreApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"NSDictionary*" completionBlock: ^(id data, NSError *error) { - handler((NSDictionary*)data, error); + if(handler) { + handler((NSDictionary*)data, error); + } } ]; } @@ -210,15 +208,19 @@ static SWGStoreApi* singletonAPI = nil; completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `orderId` when calling `getOrderById`"]; + NSParameterAssert(orderId); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"orderId"] }; + NSError* error = [NSError errorWithDomain:kSWGStoreApiErrorDomain code:kSWGStoreApiMissingParamErrorCode userInfo:userInfo]; + handler(nil, error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -226,24 +228,19 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -265,7 +262,9 @@ static SWGStoreApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"SWGOrder*" completionBlock: ^(id data, NSError *error) { - handler((SWGOrder*)data, error); + if(handler) { + handler((SWGOrder*)data, error); + } } ]; } @@ -282,31 +281,24 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -329,7 +321,9 @@ static SWGStoreApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"SWGOrder*" completionBlock: ^(id data, NSError *error) { - handler((SWGOrder*)data, error); + if(handler) { + handler((SWGOrder*)data, error); + } } ]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h similarity index 55% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h index 6f3561dfbf3..67f8ec9cbb2 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h @@ -1,97 +1,110 @@ #import #import "SWGUser.h" -#import "SWGObject.h" -#import "SWGApiClient.h" - +#import "SWGApi.h" /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ -@interface SWGUserApi: NSObject -@property(nonatomic, assign)SWGApiClient *apiClient; +@interface SWGUserApi: NSObject + +extern NSString* kSWGUserApiErrorDomain; +extern NSInteger kSWGUserApiMissingParamErrorCode; + ++(instancetype) sharedAPI; --(instancetype) initWithApiClient:(SWGApiClient *)apiClient; --(void) addHeader:(NSString*)value forKey:(NSString*)key; --(unsigned long) requestQueueSize; -+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(SWGUserApi*) sharedAPI; -/// -/// /// Create user /// This can only be done by the logged in user. /// /// @param body Created user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted /// +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; -/// -/// /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username/password supplied" /// /// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username @@ -99,26 +112,25 @@ completionHandler: (void (^)(NSString* output, NSError* error)) handler; -/// -/// /// Logs out current logged in user session /// /// /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; -/// -/// /// 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 (optional) /// +/// code:400 message:"Invalid user supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) updateUserWithUsername: (NSString*) username diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m similarity index 64% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m index 914d1822402..6ffb578ed76 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m @@ -4,24 +4,29 @@ @interface SWGUserApi () - @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; + +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; + @end @implementation SWGUserApi -static SWGUserApi* singletonAPI = nil; +NSString* kSWGUserApiErrorDomain = @"SWGUserApiErrorDomain"; +NSInteger kSWGUserApiMissingParamErrorCode = 234513; + +@synthesize apiClient = _apiClient; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; if (config.apiClient == nil) { config.apiClient = [[SWGApiClient alloc] init]; } - self.apiClient = config.apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } @@ -29,39 +34,36 @@ static SWGUserApi* singletonAPI = nil; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - self.apiClient = apiClient; - self.defaultHeaders = [NSMutableDictionary dictionary]; + _apiClient = apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { - singletonAPI = [[SWGUserApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; ++ (instancetype)sharedAPI { + static SWGUserApi *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; } -+(SWGUserApi*) sharedAPI { - if (singletonAPI == nil) { - singletonAPI = [[SWGUserApi alloc] init]; - } - return singletonAPI; +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; } -(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - --(unsigned long) requestQueueSize { +-(NSUInteger) requestQueueSize { return [SWGApiClient requestQueueSize]; } @@ -79,31 +81,24 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -126,7 +121,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -143,31 +140,24 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -190,7 +180,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -207,31 +199,24 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -254,7 +239,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -270,15 +257,19 @@ static SWGUserApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `deleteUser`"]; + NSParameterAssert(username); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"username"] }; + NSError* error = [NSError errorWithDomain:kSWGUserApiErrorDomain code:kSWGUserApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -286,24 +277,19 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -325,7 +311,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -341,15 +329,19 @@ static SWGUserApi* singletonAPI = nil; completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `getUserByName`"]; + NSParameterAssert(username); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"username"] }; + NSError* error = [NSError errorWithDomain:kSWGUserApiErrorDomain code:kSWGUserApiMissingParamErrorCode userInfo:userInfo]; + handler(nil, error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -357,24 +349,19 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -396,7 +383,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"SWGUser*" completionBlock: ^(id data, NSError *error) { - handler((SWGUser*)data, error); + if(handler) { + handler((SWGUser*)data, error); + } } ]; } @@ -416,9 +405,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -429,24 +416,19 @@ static SWGUserApi* singletonAPI = nil; if (password != nil) { queryParams[@"password"] = password; } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -468,7 +450,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: @"NSString*" completionBlock: ^(id data, NSError *error) { - handler((NSString*)data, error); + if(handler) { + handler((NSString*)data, error); + } } ]; } @@ -483,31 +467,24 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -529,7 +506,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } @@ -548,15 +527,19 @@ static SWGUserApi* singletonAPI = nil; completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `updateUser`"]; + NSParameterAssert(username); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"username"] }; + NSError* error = [NSError errorWithDomain:kSWGUserApiErrorDomain code:kSWGUserApiMissingParamErrorCode userInfo:userInfo]; + handler(error); + } + return nil; } NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -564,24 +547,19 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -604,7 +582,9 @@ static SWGUserApi* singletonAPI = nil; responseContentType: responseContentType responseType: nil completionBlock: ^(id data, NSError *error) { - handler(error); + if(handler) { + handler(error); + } } ]; } diff --git a/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..dd8e721b3b9 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h @@ -0,0 +1,31 @@ +#import +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface JSONValueTransformer (ISO8601) + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m rename to samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGApi.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGApi.h new file mode 100644 index 00000000000..93b564be3d1 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApi.h @@ -0,0 +1,42 @@ +#import +#import "SWGObject.h" +#import "SWGApiClient.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@protocol SWGApi + +@property(nonatomic, assign) SWGApiClient *apiClient; + +-(id) initWithApiClient:(SWGApiClient *)apiClient; + +-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; +-(NSString*) defaultHeaderForKey:(NSString*)key; + +-(NSUInteger) requestQueueSize; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h similarity index 76% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h index 82472ab20bf..a926598ce5f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h @@ -7,11 +7,31 @@ #import "SWGConfiguration.h" #import "SWGResponseDeserializer.h" #import "SWGSanitizer.h" +#import "SWGLogger.h" + /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ #import "SWGCategory.h" #import "SWGOrder.h" @@ -30,13 +50,6 @@ */ extern NSString *const SWGResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef SWGDebugLog - #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface SWGApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -66,7 +79,7 @@ extern NSString *const SWGResponseObjectErrorKey; * * @return The size of `queuedRequests` static variable. */ -+(unsigned long)requestQueueSize; ++(NSUInteger)requestQueueSize; /** * Sets the client unreachable @@ -117,15 +130,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -138,24 +142,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -176,19 +162,6 @@ extern NSString *const SWGResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -227,8 +200,11 @@ extern NSString *const SWGResponseObjectErrorKey; - (AFSecurityPolicy *) customSecurityPolicy; /** - * Log debug message + * SWGConfiguration return sharedConfig + * + * @return SWGConfiguration */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; +- (SWGConfiguration*) configuration; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m similarity index 67% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m index 1246dff7fca..66305707b17 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m @@ -2,7 +2,7 @@ NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { @interface SWGApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -83,54 +83,10 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { reachabilityStatus = status; } -- (void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey { +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - SWGDebugLog(message); -} - #pragma mark - Cache Methods +(void)clearCache { @@ -151,86 +107,20 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods -+(unsigned long)requestQueueSize { ++(NSUInteger)requestQueueSize { return [queuedRequests count]; } +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - SWGDebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [SWGApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; SWGDebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +184,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +211,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return; } strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -330,8 +220,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); } - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); NSString * filename = SWG__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; @@ -370,14 +259,14 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -386,15 +275,18 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; formParams = [self.sanitizer sanitizeForSerialization:formParams]; - body = [self.sanitizer sanitizeForSerialization:body]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[SWGApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = SWGPercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -438,10 +330,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -462,9 +351,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [SWGApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -485,59 +372,66 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ - SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = SWGPercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, SWGPercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = SWGPercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -549,24 +443,26 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { - if (!authSettings || [authSettings count] == 0) { + if ([authSettings count] == 0) { return; } NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = configurationAuthSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } @@ -577,7 +473,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + SWGConfiguration *config = [self configuration]; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; @@ -595,4 +491,8 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return securityPolicy; } +- (SWGConfiguration*) configuration { + return [SWGConfiguration sharedConfig]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h similarity index 59% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h index 27cfe5d6d24..b6c37405ca2 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h @@ -1,17 +1,40 @@ #import #import "SWGApiClient.h" +#import "SWGLogger.h" -/** The `SWGConfiguration` class manages the configurations for the sdk. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ @class SWGApiClient; @interface SWGConfiguration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + /** * Default api client */ @@ -37,7 +60,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +79,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -113,8 +122,6 @@ /** * Sets the prefix for API key * - * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. - * * @param apiKeyPrefix API key prefix. * @param identifier API key identifier. */ @@ -143,8 +150,33 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m similarity index 65% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m index dd1596bf8ce..24172638bba 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m @@ -2,14 +2,15 @@ @interface SWGConfiguration () -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; +@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; @end @implementation SWGConfiguration -#pragma mark - Singletion Methods +#pragma mark - Singleton Methods + (instancetype) sharedConfig { static SWGConfiguration *shardConfig = nil; @@ -30,12 +31,12 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders[@"User-Agent"] = [NSString stringWithFormat:@"Swagger-Codegen/1.0.0/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; + self.logger = [SWGLogger sharedLogger]; } return self; } @@ -43,11 +44,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +73,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +96,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -139,4 +127,34 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h new file mode 100644 index 00000000000..d9c4d4ad060 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h @@ -0,0 +1,29 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGJSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m similarity index 76% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m index 631a20a5a6e..221765e4839 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m @@ -17,19 +17,21 @@ withParameters:(id)parameters error:(NSError *__autoreleasing *)error { + if (!parameters) { + return request; + } // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } else { - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - if (parameters) { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h new file mode 100644 index 00000000000..20535a6b92e --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h @@ -0,0 +1,30 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGJSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m similarity index 78% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m index a2dd21bcf5d..73c696d341a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m @@ -1,13 +1,5 @@ #import "SWGJSONResponseSerializer.h" -static BOOL JSONParseError(NSError *error) { - if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { - return YES; - } - - return NO; -} - @implementation SWGJSONResponseSerializer /// @@ -17,7 +9,7 @@ static BOOL JSONParseError(NSError *error) { /// /// @param response The response to be processed. /// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the respnse data. +/// @param error The error that occurred while attempting to decode the response data. /// /// @return The object decoded from the specified response data. /// @@ -27,7 +19,7 @@ static BOOL JSONParseError(NSError *error) { NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; // if response data is not a valid json, return string of data. - if (JSONParseError(*error)) { + if ([self isParseError:*error]) { *error = nil; NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return responseString; @@ -36,4 +28,12 @@ static BOOL JSONParseError(NSError *error) { return responseJson; } +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h new file mode 100644 index 00000000000..cb4279f182b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h @@ -0,0 +1,72 @@ +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +#ifndef SWGDebugLogResponse +#define SWGDebugLogResponse(response, responseObject,request, error) [[SWGLogger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef SWGDebugLog +#define SWGDebugLog(format, ...) [[SWGLogger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface SWGLogger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by SWGConfiguration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m new file mode 100644 index 00000000000..322ae9678d7 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m @@ -0,0 +1,74 @@ +#import "SWGLogger.h" + +@interface SWGLogger () + +@end + +@implementation SWGLogger + ++ (instancetype) sharedLogger { + static SWGLogger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + SWGDebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h new file mode 100644 index 00000000000..be57583b8f6 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h @@ -0,0 +1,30 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGObject : JSONModel + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGObject.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h new file mode 100644 index 00000000000..69a5ab3c133 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h @@ -0,0 +1,35 @@ +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGQueryParamCollection : NSObject + +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h similarity index 50% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h index b20ead44f83..c0d7b716a01 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h @@ -1,10 +1,28 @@ #import /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ /** * A key for deserialization ErrorDomain diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h new file mode 100644 index 00000000000..59699c2bdd5 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h @@ -0,0 +1,67 @@ +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +extern NSString * SWGPercentEscapedStringFromString(NSString *string); + +@protocol SWGSanitizer + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + +@end + +@interface SWGSanitizer : NSObject + + + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m new file mode 100644 index 00000000000..a74f72afbe3 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m @@ -0,0 +1,168 @@ +#import "SWGSanitizer.h" +#import "SWGObject.h" +#import "SWGQueryParamCollection.h" +#import + +NSString * SWGPercentEscapedStringFromString(NSString *string) { + static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kSWGCharactersGeneralDelimitersToEncode stringByAppendingString:kSWGCharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +@interface SWGSanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + +@end + +@implementation SWGSanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:object]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:param]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h deleted file mode 100644 index 832f485f4f0..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h +++ /dev/null @@ -1,6 +0,0 @@ -#import -#import -#import - -@interface JSONValueTransformer (ISO8601) -@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h new file mode 100644 index 00000000000..1565724cf8c --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h @@ -0,0 +1,40 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +@protocol SWGCategory +@end + +@interface SWGCategory : SWGObject + + +@property(nonatomic) NSNumber* _id; + +@property(nonatomic) NSString* name; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m similarity index 93% rename from samples/client/petstore/objc/SwaggerClient/SWGCategory.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m index 29e3bc16226..00745d1f499 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m @@ -5,7 +5,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any } return self; @@ -29,7 +29,6 @@ NSArray *optionalProperties = @[@"_id", @"name"]; return [optionalProperties containsObject:propertyName]; - } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.h new file mode 100644 index 00000000000..021af11ec8d --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.h @@ -0,0 +1,46 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +NS_ASSUME_NONNULL_BEGIN + +@interface SWGCategoryManagedObject : NSManagedObject + + +@property (nullable, nonatomic, retain) NSNumber* _id; + +@property (nullable, nonatomic, retain) NSString* name; + +@end + +@interface SWGCategoryManagedObject (GeneratedAccessors) + + +@end + +NS_ASSUME_NONNULL_END diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.m new file mode 100644 index 00000000000..aa4d5f4b822 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObject.m @@ -0,0 +1,13 @@ +#import "SWGCategoryManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation SWGCategoryManagedObject + +@dynamic _id; +@dynamic name; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.h new file mode 100644 index 00000000000..51452aa5c89 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.h @@ -0,0 +1,46 @@ +#import +#import + + +#import "SWGCategoryManagedObject.h" +#import "SWGCategory.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGCategoryManagedObjectBuilder : NSObject + + + +-(SWGCategoryManagedObject*)createNewSWGCategoryManagedObjectInContext:(NSManagedObjectContext*)context; + +-(SWGCategoryManagedObject*)SWGCategoryManagedObjectFromSWGCategory:(SWGCategory*)Category context:(NSManagedObjectContext*)context; + +-(void)updateSWGCategoryManagedObject:(SWGCategoryManagedObject*)Category withSWGCategory:(SWGCategory*)Category2; + +-(SWGCategory*)SWGCategoryFromSWGCategoryManagedObject:(SWGCategoryManagedObject*)obj; + +-(void)updateSWGCategory:(SWGCategory*)Category withSWGCategoryManagedObject:(SWGCategoryManagedObject*)Category2; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.m new file mode 100644 index 00000000000..6c895a4c0d6 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategoryManagedObjectBuilder.m @@ -0,0 +1,53 @@ + + +#import "SWGCategoryManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation SWGCategoryManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { + } + return self; +} + +-(SWGCategoryManagedObject*)createNewSWGCategoryManagedObjectInContext:(NSManagedObjectContext*)context { + SWGCategoryManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([SWGCategoryManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-(SWGCategoryManagedObject*)SWGCategoryManagedObjectFromSWGCategory:(SWGCategory*)Category context:(NSManagedObjectContext*)context { + SWGCategoryManagedObject* newSWGCategory = [self createNewSWGCategoryManagedObjectInContext:context]; + [self updateSWGCategoryManagedObject:newSWGCategory withSWGCategory:Category]; + return newSWGCategory; +} + +-(void)updateSWGCategoryManagedObject:(SWGCategoryManagedObject*)managedObject withSWGCategory:(SWGCategory*)object { + if(!managedObject || !object) { + return; + } + managedObject._id = [object._id copy]; + managedObject.name = [object.name copy]; +} + +-(SWGCategory*)SWGCategoryFromSWGCategoryManagedObject:(SWGCategoryManagedObject*)obj { + if(!obj) { + return nil; + } + SWGCategory* newSWGCategory = [[SWGCategory alloc] init]; + [self updateSWGCategory:newSWGCategory withSWGCategoryManagedObject:obj]; + return newSWGCategory; +} + +-(void)updateSWGCategory:(SWGCategory*)newSWGCategory withSWGCategoryManagedObject:(SWGCategoryManagedObject*)obj { + newSWGCategory._id = [obj._id copy]; + newSWGCategory.name = [obj.name copy]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion b/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion new file mode 100644 index 00000000000..c38112b62d2 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion @@ -0,0 +1,8 @@ + + + + + _XCCurrentVersionName + SWGModel.xcdatamodel + + diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/SWGModel.xcdatamodel/contents b/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/SWGModel.xcdatamodel/contents new file mode 100644 index 00000000000..d6c893f1d25 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGModel.xcdatamodeld/SWGModel.xcdatamodel/contents @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h new file mode 100644 index 00000000000..5c29f61c0e6 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h @@ -0,0 +1,49 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +@protocol SWGOrder +@end + +@interface SWGOrder : SWGObject + + +@property(nonatomic) NSNumber* _id; + +@property(nonatomic) NSNumber* petId; + +@property(nonatomic) NSNumber* quantity; + +@property(nonatomic) NSDate* shipDate; +/* Order Status [optional] + */ +@property(nonatomic) NSString* status; + +@property(nonatomic) NSNumber* complete; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m similarity index 94% rename from samples/client/petstore/objc/SwaggerClient/SWGOrder.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m index d10ed802b8d..e0b44e06954 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m @@ -5,7 +5,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any } return self; @@ -29,7 +29,6 @@ NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; return [optionalProperties containsObject:propertyName]; - } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.h new file mode 100644 index 00000000000..c0d9d471bac --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.h @@ -0,0 +1,55 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +NS_ASSUME_NONNULL_BEGIN + +@interface SWGOrderManagedObject : NSManagedObject + + +@property (nullable, nonatomic, retain) NSNumber* _id; + +@property (nullable, nonatomic, retain) NSNumber* petId; + +@property (nullable, nonatomic, retain) NSNumber* quantity; + +@property (nullable, nonatomic, retain) NSDate* shipDate; +/* Order Status [optional] + */ +@property (nullable, nonatomic, retain) NSString* status; + +@property (nullable, nonatomic, retain) NSNumber* complete; + +@end + +@interface SWGOrderManagedObject (GeneratedAccessors) + + +@end + +NS_ASSUME_NONNULL_END diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.m new file mode 100644 index 00000000000..7a1b9298a95 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObject.m @@ -0,0 +1,17 @@ +#import "SWGOrderManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation SWGOrderManagedObject + +@dynamic _id; +@dynamic petId; +@dynamic quantity; +@dynamic shipDate; +@dynamic status; +@dynamic complete; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.h new file mode 100644 index 00000000000..fbabfedb404 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.h @@ -0,0 +1,46 @@ +#import +#import + + +#import "SWGOrderManagedObject.h" +#import "SWGOrder.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGOrderManagedObjectBuilder : NSObject + + + +-(SWGOrderManagedObject*)createNewSWGOrderManagedObjectInContext:(NSManagedObjectContext*)context; + +-(SWGOrderManagedObject*)SWGOrderManagedObjectFromSWGOrder:(SWGOrder*)Order context:(NSManagedObjectContext*)context; + +-(void)updateSWGOrderManagedObject:(SWGOrderManagedObject*)Order withSWGOrder:(SWGOrder*)Order2; + +-(SWGOrder*)SWGOrderFromSWGOrderManagedObject:(SWGOrderManagedObject*)obj; + +-(void)updateSWGOrder:(SWGOrder*)Order withSWGOrderManagedObject:(SWGOrderManagedObject*)Order2; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.m new file mode 100644 index 00000000000..ce1c6352b11 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrderManagedObjectBuilder.m @@ -0,0 +1,61 @@ + + +#import "SWGOrderManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation SWGOrderManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { + } + return self; +} + +-(SWGOrderManagedObject*)createNewSWGOrderManagedObjectInContext:(NSManagedObjectContext*)context { + SWGOrderManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([SWGOrderManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-(SWGOrderManagedObject*)SWGOrderManagedObjectFromSWGOrder:(SWGOrder*)Order context:(NSManagedObjectContext*)context { + SWGOrderManagedObject* newSWGOrder = [self createNewSWGOrderManagedObjectInContext:context]; + [self updateSWGOrderManagedObject:newSWGOrder withSWGOrder:Order]; + return newSWGOrder; +} + +-(void)updateSWGOrderManagedObject:(SWGOrderManagedObject*)managedObject withSWGOrder:(SWGOrder*)object { + if(!managedObject || !object) { + return; + } + managedObject._id = [object._id copy]; + managedObject.petId = [object.petId copy]; + managedObject.quantity = [object.quantity copy]; + managedObject.shipDate = [object.shipDate copy]; + managedObject.status = [object.status copy]; + managedObject.complete = [object.complete copy]; +} + +-(SWGOrder*)SWGOrderFromSWGOrderManagedObject:(SWGOrderManagedObject*)obj { + if(!obj) { + return nil; + } + SWGOrder* newSWGOrder = [[SWGOrder alloc] init]; + [self updateSWGOrder:newSWGOrder withSWGOrderManagedObject:obj]; + return newSWGOrder; +} + +-(void)updateSWGOrder:(SWGOrder*)newSWGOrder withSWGOrderManagedObject:(SWGOrderManagedObject*)obj { + newSWGOrder._id = [obj._id copy]; + newSWGOrder.petId = [obj.petId copy]; + newSWGOrder.quantity = [obj.quantity copy]; + newSWGOrder.shipDate = [obj.shipDate copy]; + newSWGOrder.status = [obj.status copy]; + newSWGOrder.complete = [obj.complete copy]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h new file mode 100644 index 00000000000..90de23fbbf5 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h @@ -0,0 +1,51 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +#import "SWGCategory.h" +#import "SWGTag.h" + + +@protocol SWGPet +@end + +@interface SWGPet : SWGObject + + +@property(nonatomic) NSNumber* _id; + +@property(nonatomic) SWGCategory* category; + +@property(nonatomic) NSString* name; + +@property(nonatomic) NSArray* photoUrls; + +@property(nonatomic) NSArray* tags; +/* pet status in the store [optional] + */ +@property(nonatomic) NSString* status; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m similarity index 94% rename from samples/client/petstore/objc/SwaggerClient/SWGPet.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m index 98e75189ed3..a1c63520dc4 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m @@ -5,7 +5,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any } return self; @@ -29,7 +29,6 @@ NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; return [optionalProperties containsObject:propertyName]; - } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.h new file mode 100644 index 00000000000..1f1c5d3cadb --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.h @@ -0,0 +1,61 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +#import "SWGCategoryManagedObject.h" +#import "SWGTagManagedObject.h" + + +NS_ASSUME_NONNULL_BEGIN + +@interface SWGPetManagedObject : NSManagedObject + + +@property (nullable, nonatomic, retain) NSNumber* _id; + +@property (nullable, nonatomic, retain) SWGCategoryManagedObject* category; + +@property (nullable, nonatomic, retain) NSString* name; + +@property (nullable, nonatomic, retain) NSArray* photoUrls; + +@property (nullable, nonatomic, retain) NSSet* tags; +/* pet status in the store [optional] + */ +@property (nullable, nonatomic, retain) NSString* status; + +@end + +@interface SWGPetManagedObject (GeneratedAccessors) + +- (void)addTagsObject:(SWGTagManagedObject *)value; +- (void)removeTagsObject:(SWGTagManagedObject *)value; +- (void)addTags:(NSSet *)values; +- (void)removeTags:(NSSet *)values; + +@end + +NS_ASSUME_NONNULL_END diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.m new file mode 100644 index 00000000000..7526628c42b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObject.m @@ -0,0 +1,17 @@ +#import "SWGPetManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation SWGPetManagedObject + +@dynamic _id; +@dynamic category; +@dynamic name; +@dynamic photoUrls; +@dynamic tags; +@dynamic status; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.h new file mode 100644 index 00000000000..09161aca3d7 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.h @@ -0,0 +1,50 @@ +#import +#import + +#import "SWGCategoryManagedObjectBuilder.h" +#import "SWGTagManagedObjectBuilder.h" + +#import "SWGPetManagedObject.h" +#import "SWGPet.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGPetManagedObjectBuilder : NSObject + +@property (nonatomic, strong) SWGCategoryManagedObjectBuilder * categoryBuilder; +@property (nonatomic, strong) SWGTagManagedObjectBuilder * tagsBuilder; + + +-(SWGPetManagedObject*)createNewSWGPetManagedObjectInContext:(NSManagedObjectContext*)context; + +-(SWGPetManagedObject*)SWGPetManagedObjectFromSWGPet:(SWGPet*)Pet context:(NSManagedObjectContext*)context; + +-(void)updateSWGPetManagedObject:(SWGPetManagedObject*)Pet withSWGPet:(SWGPet*)Pet2; + +-(SWGPet*)SWGPetFromSWGPetManagedObject:(SWGPetManagedObject*)obj; + +-(void)updateSWGPet:(SWGPet*)Pet withSWGPetManagedObject:(SWGPetManagedObject*)Pet2; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.m new file mode 100644 index 00000000000..84a3463ea78 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGPetManagedObjectBuilder.m @@ -0,0 +1,83 @@ + + +#import "SWGPetManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation SWGPetManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { + _categoryBuilder = [[SWGCategoryManagedObjectBuilder alloc] init]; + _tagsBuilder = [[SWGTagManagedObjectBuilder alloc] init]; + } + return self; +} + +-(SWGPetManagedObject*)createNewSWGPetManagedObjectInContext:(NSManagedObjectContext*)context { + SWGPetManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([SWGPetManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-(SWGPetManagedObject*)SWGPetManagedObjectFromSWGPet:(SWGPet*)Pet context:(NSManagedObjectContext*)context { + SWGPetManagedObject* newSWGPet = [self createNewSWGPetManagedObjectInContext:context]; + [self updateSWGPetManagedObject:newSWGPet withSWGPet:Pet]; + return newSWGPet; +} + +-(void)updateSWGPetManagedObject:(SWGPetManagedObject*)managedObject withSWGPet:(SWGPet*)object { + if(!managedObject || !object) { + return; + } + managedObject._id = [object._id copy]; + + if(!managedObject.category) { + managedObject.category = [self.categoryBuilder SWGCategoryManagedObjectFromSWGCategory:object.category context:managedObject.managedObjectContext]; + } else { + [self.categoryBuilder updateSWGCategoryManagedObject:managedObject.category withSWGCategory:object.category]; + } + managedObject.name = [object.name copy]; + managedObject.photoUrls = [object.photoUrls copy]; + if(object.tags) { + NSMutableSet * convertedObjs = [NSMutableSet set]; + for (id innerObject in object.tags) { + id convertedObj = [self.tagsBuilder SWGTagManagedObjectFromSWGTag:innerObject context:managedObject.managedObjectContext]; + [convertedObjs addObject:convertedObj]; + } + managedObject.tags = convertedObjs; + } + managedObject.status = [object.status copy]; +} + +-(SWGPet*)SWGPetFromSWGPetManagedObject:(SWGPetManagedObject*)obj { + if(!obj) { + return nil; + } + SWGPet* newSWGPet = [[SWGPet alloc] init]; + [self updateSWGPet:newSWGPet withSWGPetManagedObject:obj]; + return newSWGPet; +} + +-(void)updateSWGPet:(SWGPet*)newSWGPet withSWGPetManagedObject:(SWGPetManagedObject*)obj { + newSWGPet._id = [obj._id copy]; + newSWGPet.category = [self.categoryBuilder SWGCategoryFromSWGCategoryManagedObject:obj.category]; + newSWGPet.name = [obj.name copy]; + newSWGPet.photoUrls = [obj.photoUrls copy]; + if(obj.tags != nil) { + NSMutableArray* convertedObjs = [NSMutableArray array]; + for (id innerObject in obj.tags) { + id convertedObj = [self.tagsBuilder SWGTagFromSWGTagManagedObject:innerObject]; + [convertedObjs addObject:convertedObj]; + } + newSWGPet.tags = (NSArray*)convertedObjs; + } + + newSWGPet.status = [obj.status copy]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h new file mode 100644 index 00000000000..97aa6162af6 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h @@ -0,0 +1,40 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +@protocol SWGTag +@end + +@interface SWGTag : SWGObject + + +@property(nonatomic) NSNumber* _id; + +@property(nonatomic) NSString* name; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m similarity index 93% rename from samples/client/petstore/objc/SwaggerClient/SWGTag.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m index 8ad1742750d..e71829873d1 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m @@ -5,7 +5,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any } return self; @@ -29,7 +29,6 @@ NSArray *optionalProperties = @[@"_id", @"name"]; return [optionalProperties containsObject:propertyName]; - } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.h new file mode 100644 index 00000000000..cca64c327af --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.h @@ -0,0 +1,46 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +NS_ASSUME_NONNULL_BEGIN + +@interface SWGTagManagedObject : NSManagedObject + + +@property (nullable, nonatomic, retain) NSNumber* _id; + +@property (nullable, nonatomic, retain) NSString* name; + +@end + +@interface SWGTagManagedObject (GeneratedAccessors) + + +@end + +NS_ASSUME_NONNULL_END diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.m new file mode 100644 index 00000000000..9f616af1ea8 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObject.m @@ -0,0 +1,13 @@ +#import "SWGTagManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation SWGTagManagedObject + +@dynamic _id; +@dynamic name; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.h new file mode 100644 index 00000000000..3c54b8f0660 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.h @@ -0,0 +1,46 @@ +#import +#import + + +#import "SWGTagManagedObject.h" +#import "SWGTag.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGTagManagedObjectBuilder : NSObject + + + +-(SWGTagManagedObject*)createNewSWGTagManagedObjectInContext:(NSManagedObjectContext*)context; + +-(SWGTagManagedObject*)SWGTagManagedObjectFromSWGTag:(SWGTag*)Tag context:(NSManagedObjectContext*)context; + +-(void)updateSWGTagManagedObject:(SWGTagManagedObject*)Tag withSWGTag:(SWGTag*)Tag2; + +-(SWGTag*)SWGTagFromSWGTagManagedObject:(SWGTagManagedObject*)obj; + +-(void)updateSWGTag:(SWGTag*)Tag withSWGTagManagedObject:(SWGTagManagedObject*)Tag2; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.m new file mode 100644 index 00000000000..2e26bfc555c --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGTagManagedObjectBuilder.m @@ -0,0 +1,53 @@ + + +#import "SWGTagManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation SWGTagManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { + } + return self; +} + +-(SWGTagManagedObject*)createNewSWGTagManagedObjectInContext:(NSManagedObjectContext*)context { + SWGTagManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([SWGTagManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-(SWGTagManagedObject*)SWGTagManagedObjectFromSWGTag:(SWGTag*)Tag context:(NSManagedObjectContext*)context { + SWGTagManagedObject* newSWGTag = [self createNewSWGTagManagedObjectInContext:context]; + [self updateSWGTagManagedObject:newSWGTag withSWGTag:Tag]; + return newSWGTag; +} + +-(void)updateSWGTagManagedObject:(SWGTagManagedObject*)managedObject withSWGTag:(SWGTag*)object { + if(!managedObject || !object) { + return; + } + managedObject._id = [object._id copy]; + managedObject.name = [object.name copy]; +} + +-(SWGTag*)SWGTagFromSWGTagManagedObject:(SWGTagManagedObject*)obj { + if(!obj) { + return nil; + } + SWGTag* newSWGTag = [[SWGTag alloc] init]; + [self updateSWGTag:newSWGTag withSWGTagManagedObject:obj]; + return newSWGTag; +} + +-(void)updateSWGTag:(SWGTag*)newSWGTag withSWGTagManagedObject:(SWGTagManagedObject*)obj { + newSWGTag._id = [obj._id copy]; + newSWGTag.name = [obj.name copy]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h new file mode 100644 index 00000000000..2c94220a57e --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h @@ -0,0 +1,53 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +@protocol SWGUser +@end + +@interface SWGUser : SWGObject + + +@property(nonatomic) NSNumber* _id; + +@property(nonatomic) NSString* username; + +@property(nonatomic) NSString* firstName; + +@property(nonatomic) NSString* lastName; + +@property(nonatomic) NSString* email; + +@property(nonatomic) NSString* password; + +@property(nonatomic) NSString* phone; +/* User Status [optional] + */ +@property(nonatomic) NSNumber* userStatus; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m similarity index 94% rename from samples/client/petstore/objc/SwaggerClient/SWGUser.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m index 2551108cb5f..c8195660df6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m @@ -5,7 +5,7 @@ - (instancetype)init { self = [super init]; if (self) { - // initalise property's default value, if any + // initialize property's default value, if any } return self; @@ -29,7 +29,6 @@ NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; return [optionalProperties containsObject:propertyName]; - } @end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.h new file mode 100644 index 00000000000..30405f3658a --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.h @@ -0,0 +1,59 @@ +#import +#import + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + + + +NS_ASSUME_NONNULL_BEGIN + +@interface SWGUserManagedObject : NSManagedObject + + +@property (nullable, nonatomic, retain) NSNumber* _id; + +@property (nullable, nonatomic, retain) NSString* username; + +@property (nullable, nonatomic, retain) NSString* firstName; + +@property (nullable, nonatomic, retain) NSString* lastName; + +@property (nullable, nonatomic, retain) NSString* email; + +@property (nullable, nonatomic, retain) NSString* password; + +@property (nullable, nonatomic, retain) NSString* phone; +/* User Status [optional] + */ +@property (nullable, nonatomic, retain) NSNumber* userStatus; + +@end + +@interface SWGUserManagedObject (GeneratedAccessors) + + +@end + +NS_ASSUME_NONNULL_END diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.m new file mode 100644 index 00000000000..f6779715858 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObject.m @@ -0,0 +1,19 @@ +#import "SWGUserManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation SWGUserManagedObject + +@dynamic _id; +@dynamic username; +@dynamic firstName; +@dynamic lastName; +@dynamic email; +@dynamic password; +@dynamic phone; +@dynamic userStatus; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.h new file mode 100644 index 00000000000..1c39fa6de5b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.h @@ -0,0 +1,46 @@ +#import +#import + + +#import "SWGUserManagedObject.h" +#import "SWGUser.h" + +/** +* Swagger Petstore +* 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 +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* 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. +* +* 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. +*/ + +@interface SWGUserManagedObjectBuilder : NSObject + + + +-(SWGUserManagedObject*)createNewSWGUserManagedObjectInContext:(NSManagedObjectContext*)context; + +-(SWGUserManagedObject*)SWGUserManagedObjectFromSWGUser:(SWGUser*)User context:(NSManagedObjectContext*)context; + +-(void)updateSWGUserManagedObject:(SWGUserManagedObject*)User withSWGUser:(SWGUser*)User2; + +-(SWGUser*)SWGUserFromSWGUserManagedObject:(SWGUserManagedObject*)obj; + +-(void)updateSWGUser:(SWGUser*)User withSWGUserManagedObject:(SWGUserManagedObject*)User2; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.m new file mode 100644 index 00000000000..8086e6a20e6 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Model/SWGUserManagedObjectBuilder.m @@ -0,0 +1,65 @@ + + +#import "SWGUserManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation SWGUserManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { + } + return self; +} + +-(SWGUserManagedObject*)createNewSWGUserManagedObjectInContext:(NSManagedObjectContext*)context { + SWGUserManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([SWGUserManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-(SWGUserManagedObject*)SWGUserManagedObjectFromSWGUser:(SWGUser*)User context:(NSManagedObjectContext*)context { + SWGUserManagedObject* newSWGUser = [self createNewSWGUserManagedObjectInContext:context]; + [self updateSWGUserManagedObject:newSWGUser withSWGUser:User]; + return newSWGUser; +} + +-(void)updateSWGUserManagedObject:(SWGUserManagedObject*)managedObject withSWGUser:(SWGUser*)object { + if(!managedObject || !object) { + return; + } + managedObject._id = [object._id copy]; + managedObject.username = [object.username copy]; + managedObject.firstName = [object.firstName copy]; + managedObject.lastName = [object.lastName copy]; + managedObject.email = [object.email copy]; + managedObject.password = [object.password copy]; + managedObject.phone = [object.phone copy]; + managedObject.userStatus = [object.userStatus copy]; +} + +-(SWGUser*)SWGUserFromSWGUserManagedObject:(SWGUserManagedObject*)obj { + if(!obj) { + return nil; + } + SWGUser* newSWGUser = [[SWGUser alloc] init]; + [self updateSWGUser:newSWGUser withSWGUserManagedObject:obj]; + return newSWGUser; +} + +-(void)updateSWGUser:(SWGUser*)newSWGUser withSWGUserManagedObject:(SWGUserManagedObject*)obj { + newSWGUser._id = [obj._id copy]; + newSWGUser.username = [obj.username copy]; + newSWGUser.firstName = [obj.firstName copy]; + newSWGUser.lastName = [obj.lastName copy]; + newSWGUser.email = [obj.email copy]; + newSWGUser.password = [obj.password copy]; + newSWGUser.phone = [obj.phone copy]; + newSWGUser.userStatus = [obj.userStatus copy]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h deleted file mode 100644 index 983fd610123..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h +++ /dev/null @@ -1,22 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGCategory -@end - -@interface SWGCategory : SWGObject - - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSString* name; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h b/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h deleted file mode 100644 index 49dd7fca3e2..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h +++ /dev/null @@ -1,5 +0,0 @@ -#import -#import - -@interface SWGJSONRequestSerializer : AFJSONRequestSerializer -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h b/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h deleted file mode 100644 index 16cda122217..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h +++ /dev/null @@ -1,6 +0,0 @@ -#import -#import - -@interface SWGJSONResponseSerializer : AFJSONResponseSerializer - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.h b/samples/client/petstore/objc/SwaggerClient/SWGObject.h deleted file mode 100644 index fb27b4a4ebb..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGObject.h +++ /dev/null @@ -1,5 +0,0 @@ -#import -#import - -@interface SWGObject : JSONModel -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h deleted file mode 100644 index 48a7cf0d6c1..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ /dev/null @@ -1,31 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGOrder -@end - -@interface SWGOrder : SWGObject - - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSNumber* petId; - -@property(nonatomic) NSNumber* quantity; - -@property(nonatomic) NSDate* shipDate; -/* Order Status [optional] - */ -@property(nonatomic) NSString* status; - -@property(nonatomic) NSNumber* complete; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h deleted file mode 100644 index 2f83af6c4e1..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ /dev/null @@ -1,33 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import "SWGCategory.h" -#import "SWGTag.h" - - -@protocol SWGPet -@end - -@interface SWGPet : SWGObject - - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) SWGCategory* category; - -@property(nonatomic) NSString* name; - -@property(nonatomic) NSArray* photoUrls; - -@property(nonatomic) NSArray* tags; -/* pet status in the store [optional] - */ -@property(nonatomic) NSString* status; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h b/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h deleted file mode 100644 index 3b771881b0f..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h +++ /dev/null @@ -1,11 +0,0 @@ -#import - -@interface SWGQueryParamCollection : NSObject - -@property(nonatomic, readonly) NSArray* values; -@property(nonatomic, readonly) NSString* format; - -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h deleted file mode 100644 index 5803999f362..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h +++ /dev/null @@ -1,29 +0,0 @@ -#import - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -@protocol SWGSanitizer - -/** - * Sanitize object for request - * - * @param object The query/path/header/form/body param to be sanitized. - */ -- (id) sanitizeForSerialization:(id) object; - -/** - * Convert parameter to NSString - */ -- (NSString *) parameterToString: (id) param; - -@end - -@interface SWGSanitizer : NSObject - - - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m deleted file mode 100644 index 3f1dea7726e..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m +++ /dev/null @@ -1,82 +0,0 @@ -#import "SWGSanitizer.h" -#import "SWGObject.h" -#import "SWGQueryParamCollection.h" -#import - -@interface SWGSanitizer () - -@end - -@implementation SWGSanitizer - -- (id) sanitizeForSerialization:(id) object { - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - [sanitizedObjs addObject:sanitizedObj]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - sanitizedObjs[key] = sanitizedObj; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[SWGObject class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - -- (NSString *) parameterToString:(id)param { - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam = [NSMutableArray array]; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h deleted file mode 100644 index d86eb23a046..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ /dev/null @@ -1,74 +0,0 @@ -#import -#import "SWGOrder.h" -#import "SWGObject.h" -#import "SWGApiClient.h" - - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -@interface SWGStoreApi: NSObject - -@property(nonatomic, assign)SWGApiClient *apiClient; - --(instancetype) initWithApiClient:(SWGApiClient *)apiClient; --(void) addHeader:(NSString*)value forKey:(NSString*)key; --(unsigned long) requestQueueSize; -+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(SWGStoreApi*) sharedAPI; -/// -/// -/// 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 -/// -/// -/// @return --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId - completionHandler: (void (^)(NSError* error)) handler; - - -/// -/// -/// Returns pet inventories by status -/// Returns a map of status codes to quantities -/// -/// -/// -/// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: - (void (^)(NSDictionary* output, NSError* error)) handler; - - -/// -/// -/// 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 -/// -/// -/// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId - completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - - -/// -/// -/// Place an order for a pet -/// -/// -/// @param body order placed for purchasing the pet (optional) -/// -/// -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body - completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - - - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/SWGTag.h deleted file mode 100644 index 97e95807550..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.h +++ /dev/null @@ -1,22 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGTag -@end - -@interface SWGTag : SWGObject - - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSString* name; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/SWGUser.h deleted file mode 100644 index 6ba19e632b8..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.h +++ /dev/null @@ -1,35 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGUser -@end - -@interface SWGUser : SWGObject - - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSString* username; - -@property(nonatomic) NSString* firstName; - -@property(nonatomic) NSString* lastName; - -@property(nonatomic) NSString* email; - -@property(nonatomic) NSString* password; - -@property(nonatomic) NSString* phone; -/* User Status [optional] - */ -@property(nonatomic) NSNumber* userStatus; - -@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index f7274144997..1a8aa88ce42 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -21,8 +21,10 @@ 6003F5BA195388D20070C39A /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 6003F5B8195388D20070C39A /* InfoPlist.strings */; }; 6003F5BC195388D20070C39A /* Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 6003F5BB195388D20070C39A /* Tests.m */; }; 94BE6BE84795B5034A811E61 /* libPods-SwaggerClient_Example.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */; }; + B2ADC0B1C8A60A05C48B4DF7 /* DatabaseHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = B2ADC55130D5E329ED945E8F /* DatabaseHelper.m */; }; B2ADC17C287DCABF329BA8AC /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = B2ADC7027D4B025ABCA7999F /* Main.storyboard */; }; B2ADC2D632658A5F73C6CE66 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = B2ADC65E342ADA697322D68C /* Images.xcassets */; }; + B2ADC3C7634D15595DD14814 /* BuildersTest.m in Sources */ = {isa = PBXBuildFile; fileRef = B2ADC838FCC22F4BC6C41106 /* BuildersTest.m */; }; B2ADC56977372855A63F4E4D /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = B2ADC084A2C0BDF217832B03 /* Launch Screen.storyboard */; }; CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0ADB471B5F95D6008A2729 /* PetTest.m */; }; CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF8F71381B5F73AC00162980 /* DeserializationTest.m */; }; @@ -66,8 +68,11 @@ 73CCD82196AABD64F2807C7B /* Pods-SwaggerClient_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient_Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests.debug.xcconfig"; sourceTree = ""; }; 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SwaggerClient_Example.a"; sourceTree = BUILT_PRODUCTS_DIR; }; B2ADC084A2C0BDF217832B03 /* Launch Screen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = "Launch Screen.storyboard"; path = "SwaggerClient/Launch Screen.storyboard"; sourceTree = ""; }; + B2ADC2F3483B3117A00FA91C /* DatabaseHelper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DatabaseHelper.h; sourceTree = ""; }; + B2ADC55130D5E329ED945E8F /* DatabaseHelper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DatabaseHelper.m; sourceTree = ""; }; B2ADC65E342ADA697322D68C /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = SwaggerClient/Images.xcassets; sourceTree = ""; }; B2ADC7027D4B025ABCA7999F /* Main.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Main.storyboard; path = SwaggerClient/Main.storyboard; sourceTree = ""; }; + B2ADC838FCC22F4BC6C41106 /* BuildersTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BuildersTest.m; sourceTree = ""; }; BFB4BE760737508B3CFC23B2 /* Pods-SwaggerClient_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient_Example.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example.release.xcconfig"; sourceTree = ""; }; CF0ADB471B5F95D6008A2729 /* PetTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetTest.m; sourceTree = ""; }; CF8F71381B5F73AC00162980 /* DeserializationTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DeserializationTest.m; sourceTree = ""; }; @@ -176,6 +181,8 @@ CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */, 6003F5BB195388D20070C39A /* Tests.m */, 6003F5B6195388D20070C39A /* Supporting Files */, + B2ADC838FCC22F4BC6C41106 /* BuildersTest.m */, + B2ADCA62DE4AC0F5BAB42208 /* Helpers */, ); path = Tests; sourceTree = ""; @@ -201,6 +208,15 @@ name = "Podspec Metadata"; sourceTree = ""; }; + B2ADCA62DE4AC0F5BAB42208 /* Helpers */ = { + isa = PBXGroup; + children = ( + B2ADC2F3483B3117A00FA91C /* DatabaseHelper.h */, + B2ADC55130D5E329ED945E8F /* DatabaseHelper.m */, + ); + path = Helpers; + sourceTree = ""; + }; CCE77F10C6D41F74B075ECD0 /* Pods */ = { isa = PBXGroup; children = ( @@ -422,6 +438,8 @@ CFDFB4151B3D000B009739C5 /* SWGApiClientTest.m in Sources */, CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */, CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */, + B2ADC3C7634D15595DD14814 /* BuildersTest.m in Sources */, + B2ADC0B1C8A60A05C48B4DF7 /* DatabaseHelper.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index 4405438e7ee..7f8e3d67881 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -34,7 +34,7 @@ - (SWGPet*) createPet { SWGPet * pet = [[SWGPet alloc] init]; - pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet._id = @((long) [[NSDate date] timeIntervalSince1970]); pet.name = @"monkey"; SWGCategory * category = [[SWGCategory alloc] init]; @@ -48,11 +48,11 @@ SWGTag *tag2 = [[SWGTag alloc] init]; tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; tag2.name = @"test tag 2"; - pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + pet.tags = (NSArray *) @[tag1, tag2]; pet.status = @"available"; - NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + NSArray * photos = @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]; pet.photoUrls = photos; return pet; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/BuildersTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/BuildersTest.m new file mode 100644 index 00000000000..c822d59d799 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/BuildersTest.m @@ -0,0 +1,117 @@ +// +// BuildersTest.m +// SwaggerClient +// +// Created by mmackowiak on 16.05.2016. +// Copyright (c) 2016 geekerzp. All rights reserved. +// + +#import +#import +#import "SWGPetManagedObject.h" +#import "SWGPetManagedObjectBuilder.h" +#import "DatabaseHelper.h" +#import "SWGUserManagedObject.h" +#import "SWGUserManagedObjectBuilder.h" +#import "SWGOrderManagedObjectBuilder.h" + +@interface BuildersTest : XCTestCase { + SWGPet *pet; + SWGUser* user; + SWGOrder *order; + NSManagedObjectContext *context; +} + +@end + +@implementation BuildersTest + +- (void)setUp { + [super setUp]; + + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" }], + }; + NSError * error; + pet = [[SWGPet alloc] initWithDictionary:petDict error:&error]; + XCTAssertNil(error); + + NSDictionary *userDict = @{ + @"id": @1, + @"email": @"test@test.com", + @"firstName": @"firstName", + @"lastName": @"lastName", + @"password": @"password", + @"username": @"username", + @"phone": @"57676767", + }; + error = nil; + user = [[SWGUser alloc] initWithDictionary:userDict error:&error]; + XCTAssertNil(error); + + NSDictionary *orderDict = @{ + @"id": @324, + @"petId": @234, + @"quantity": @12, + @"shipDate": @"1997-07-16T19:20:30+00:00", + @"status": @"status", + @"complete": @1, + }; + error = nil; + order = [[SWGOrder alloc] initWithDictionary:orderDict error:&error]; + XCTAssertNil(error); + + context = [DatabaseHelper createContextWithModelName:@"SWGModel"]; + + +} + +- (void)testSWGPetExample { + SWGPetManagedObjectBuilder* builder = [[SWGPetManagedObjectBuilder alloc] init]; + + SWGPetManagedObject * managedObject = [builder SWGPetManagedObjectFromSWGPet:pet context:context]; + SWGPet *pet2 = [builder SWGPetFromSWGPetManagedObject:managedObject]; + NSError * error; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + [context deleteObject:managedObject]; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + XCTAssertEqualObjects(pet.description,pet2.description); + +} + + +- (void)testSWGUserExample { + SWGUserManagedObjectBuilder * builder = [[SWGUserManagedObjectBuilder alloc] init]; + SWGUserManagedObject * managedObject = [builder SWGUserManagedObjectFromSWGUser:user context:context]; + SWGUser *user2 = [builder SWGUserFromSWGUserManagedObject:managedObject]; + NSError * error; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + [context deleteObject:managedObject]; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + XCTAssertEqualObjects(user.description,user2.description); + +} + +- (void)testSWGOrderExample { + SWGOrderManagedObjectBuilder * builder = [[SWGOrderManagedObjectBuilder alloc] init]; + SWGOrderManagedObject * managedObject = [builder SWGOrderManagedObjectFromSWGOrder:order context:context]; + SWGOrder *order2 = [builder SWGOrderFromSWGOrderManagedObject:managedObject]; + NSError * error; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + [context deleteObject:managedObject]; + XCTAssertTrue([context save:&error]); + XCTAssertNil(error); + + XCTAssertEqualObjects(order.description,order2.description); + +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.h b/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.h new file mode 100644 index 00000000000..8216e012a32 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.h @@ -0,0 +1,14 @@ +#import +#import + +@interface DatabaseHelper : NSObject + ++ (NSManagedObjectContext *)createContextWithModelName:(NSString *)mName; + ++ (void)clearContext:(NSManagedObjectContext *)ctx fromEntitiesWithName:(NSString *)entityName; + ++ (NSManagedObjectModel *)createModelWithModelName:(NSString *)mName; + ++ (NSManagedObjectContext *)createDatabaseWithModel:(NSManagedObjectModel*)model; + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.m new file mode 100644 index 00000000000..3433ac19ddb --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/Helpers/DatabaseHelper.m @@ -0,0 +1,42 @@ +#import "DatabaseHelper.h" + +@implementation DatabaseHelper + + ++ (NSManagedObjectContext *)createContextWithModelName:(NSString *)mName { + NSManagedObjectModel *model = [self createModelWithModelName:mName]; + return [self createDatabaseWithModel:model]; +} + ++ (NSManagedObjectContext *)createDatabaseWithModel:(NSManagedObjectModel*)model { + NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; + [coordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil]; + + NSManagedObjectContext *testingContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; + [testingContext setPersistentStoreCoordinator:coordinator]; + [testingContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy]; + return testingContext; +} + ++ (NSManagedObjectModel *)createModelWithModelName:(NSString *)mName { + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + NSString *path = [bundle pathForResource:mName ofType:@"momd"]; + NSAssert(path, @"Missing Model for name: %@",mName); + NSURL *modURL = [NSURL fileURLWithPath:path]; + return [[NSManagedObjectModel alloc] initWithContentsOfURL:modURL]; +} + ++ (void)clearContext:(NSManagedObjectContext *)ctx fromEntitiesWithName:(NSString *)entityName { + NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; + [fetch setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:ctx]]; + NSError *error = nil; + NSArray *result = [ctx executeFetchRequest:fetch error:&error]; + if (error) { + NSLog(@"Failed clearing context from entities with name [%@]", error); + } + for (id basket in result) { + [ctx deleteObject:basket]; + } +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index 7ddc817e9ef..f472c4d6ab5 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -1,7 +1,6 @@ #import #import #import -#import @interface PetApiTest : XCTestCase { @private @@ -165,13 +164,13 @@ which causes an exception when deserializing the data SWGTag* tag = [[SWGTag alloc] init]; tag.name = @"tony"; NSLog(@"%@", pet._id); - pet.tags = (id)[[NSArray alloc] initWithObjects:tag, nil]; + pet.tags = (id) @[tag]; [api addPetWithBody:pet completionHandler:^(NSError *error) { if(error) { XCTFail(@"got error %@", error); } - NSArray* tags = [[NSArray alloc] initWithObjects:@"tony", nil]; + NSArray* tags = @[@"tony",@"tony2"]; [api findPetsByTagsWithTags:tags completionHandler:^(NSArray *output, NSError *error) { if(error){ @@ -275,7 +274,7 @@ which causes an exception when deserializing the data - (SWGPet*) createPet { SWGPet * pet = [[SWGPet alloc] init]; - pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet._id = @((long) [[NSDate date] timeIntervalSince1970]); pet.name = @"monkey"; SWGCategory * category = [[SWGCategory alloc] init]; @@ -289,11 +288,11 @@ which causes an exception when deserializing the data SWGTag *tag2 = [[SWGTag alloc] init]; tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; tag2.name = @"test tag 2"; - pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + pet.tags = (NSArray *) @[tag1, tag2]; pet.status = @"available"; - NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + NSArray * photos = @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]; pet.photoUrls = photos; return pet; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index ed87d8f9e2d..335e4f50bb2 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -25,38 +25,64 @@ NSArray *accepts = nil; accepts = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"text/plain, application/xml"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"text/plain, application/xml"); accepts = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @""); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @""); } - (void)testSelectHeaderContentType { NSArray *contentTypes = nil; - + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + contentTypes = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); - + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + contentTypes = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"text/plain"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"text/plain"); contentTypes = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); } - (void)testConfiguration { diff --git a/samples/client/petstore/objc/docs/SWGPetApi.md b/samples/client/petstore/objc/docs/SWGPetApi.md index a07f0cf067c..d702c353855 100644 --- a/samples/client/petstore/objc/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/docs/SWGPetApi.md @@ -34,23 +34,15 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; SWGPet* body = [[SWGPet alloc] init]; // Pet object that needs to be added to the store (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Add a new pet to the store - [apiInstance addPetWithBody:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->addPet: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Add a new pet to the store +[apiInstance addPetWithBody:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGPetApi->addPet: %@", error); + } + }]; ``` ### Parameters @@ -96,24 +88,16 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; NSNumber* petId = @789; // Pet id to delete NSString* apiKey = @"apiKey_example"; // (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Deletes a pet - [apiInstance deletePetWithPetId:petId - apiKey:apiKey - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->deletePet: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Deletes a pet +[apiInstance deletePetWithPetId:petId + apiKey:apiKey + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGPetApi->deletePet: %@", error); + } + }]; ``` ### Parameters @@ -158,26 +142,18 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; NSArray* status = @[@"available"]; // Status values that need to be considered for filter (optional) (default to available) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Finds Pets by status - [apiInstance findPetsByStatusWithStatus:status - completionHandler: ^(NSArray* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->findPetsByStatus: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Finds Pets by status +[apiInstance findPetsByStatusWithStatus:status + completionHandler: ^(NSArray* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGPetApi->findPetsByStatus: %@", error); + } + }]; ``` ### Parameters @@ -221,26 +197,18 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; NSArray* tags = @[@"tags_example"]; // Tags to filter by (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Finds Pets by tags - [apiInstance findPetsByTagsWithTags:tags - completionHandler: ^(NSArray* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->findPetsByTags: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Finds Pets by tags +[apiInstance findPetsByTagsWithTags:tags + completionHandler: ^(NSArray* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGPetApi->findPetsByTags: %@", error); + } + }]; ``` ### Parameters @@ -289,26 +257,18 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; NSNumber* petId = @789; // ID of pet that needs to be fetched -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Find pet by ID - [apiInstance getPetByIdWithPetId:petId - completionHandler: ^(SWGPet* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->getPetById: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Find pet by ID +[apiInstance getPetByIdWithPetId:petId + completionHandler: ^(SWGPet* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGPetApi->getPetById: %@", error); + } + }]; ``` ### Parameters @@ -352,23 +312,15 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; SWGPet* body = [[SWGPet alloc] init]; // Pet object that needs to be added to the store (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Update an existing pet - [apiInstance updatePetWithBody:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->updatePet: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Update an existing pet +[apiInstance updatePetWithBody:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGPetApi->updatePet: %@", error); + } + }]; ``` ### Parameters @@ -416,25 +368,17 @@ NSString* petId = @"petId_example"; // ID of pet that needs to be updated NSString* name = @"name_example"; // Updated name of the pet (optional) NSString* status = @"status_example"; // Updated status of the pet (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // Updates a pet in the store with form data - [apiInstance updatePetWithFormWithPetId:petId - name:name - status:status - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->updatePetWithForm: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Updates a pet in the store with form data +[apiInstance updatePetWithFormWithPetId:petId + name:name + status:status + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGPetApi->updatePetWithForm: %@", error); + } + }]; ``` ### Parameters @@ -484,25 +428,17 @@ NSNumber* petId = @789; // ID of pet to update NSString* additionalMetadata = @"additionalMetadata_example"; // Additional data to pass to server (optional) NSURL* file = [NSURL fileURLWithPath:@"/path/to/file.txt"]; // file to upload (optional) -@try -{ - SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; +SWGPetApi*apiInstance = [[SWGPetApi alloc] init]; - // uploads an image - [apiInstance uploadFileWithPetId:petId - additionalMetadata:additionalMetadata - file:file - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGPetApi->uploadFile: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// uploads an image +[apiInstance uploadFileWithPetId:petId + additionalMetadata:additionalMetadata + file:file + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGPetApi->uploadFile: %@", error); + } + }]; ``` ### Parameters diff --git a/samples/client/petstore/objc/docs/SWGStoreApi.md b/samples/client/petstore/objc/docs/SWGStoreApi.md index 29dfde60aa7..12bcef79a40 100644 --- a/samples/client/petstore/objc/docs/SWGStoreApi.md +++ b/samples/client/petstore/objc/docs/SWGStoreApi.md @@ -25,23 +25,15 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non NSString* orderId = @"orderId_example"; // ID of the order that needs to be deleted -@try -{ - SWGStoreApi *apiInstance = [[SWGStoreApi alloc] init]; +SWGStoreApi*apiInstance = [[SWGStoreApi alloc] init]; - // Delete purchase order by ID - [apiInstance deleteOrderWithOrderId:orderId - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGStoreApi->deleteOrder: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Delete purchase order by ID +[apiInstance deleteOrderWithOrderId:orderId + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGStoreApi->deleteOrder: %@", error); + } + }]; ``` ### Parameters @@ -86,26 +78,18 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; -@try -{ - SWGStoreApi *apiInstance = [[SWGStoreApi alloc] init]; +SWGStoreApi*apiInstance = [[SWGStoreApi alloc] init]; - // Returns pet inventories by status - [apiInstance getInventoryWithCompletionHandler: - ^(NSDictionary* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGStoreApi->getInventory: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Returns pet inventories by status +[apiInstance getInventoryWithCompletionHandler: + ^(NSDictionary* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGStoreApi->getInventory: %@", error); + } + }]; ``` ### Parameters @@ -141,26 +125,18 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge NSString* orderId = @"orderId_example"; // ID of pet that needs to be fetched -@try -{ - SWGStoreApi *apiInstance = [[SWGStoreApi alloc] init]; +SWGStoreApi*apiInstance = [[SWGStoreApi alloc] init]; - // Find purchase order by ID - [apiInstance getOrderByIdWithOrderId:orderId - completionHandler: ^(SWGOrder* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGStoreApi->getOrderById: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Find purchase order by ID +[apiInstance getOrderByIdWithOrderId:orderId + completionHandler: ^(SWGOrder* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGStoreApi->getOrderById: %@", error); + } + }]; ``` ### Parameters @@ -199,26 +175,18 @@ Place an order for a pet SWGOrder* body = [[SWGOrder alloc] init]; // order placed for purchasing the pet (optional) -@try -{ - SWGStoreApi *apiInstance = [[SWGStoreApi alloc] init]; +SWGStoreApi*apiInstance = [[SWGStoreApi alloc] init]; - // Place an order for a pet - [apiInstance placeOrderWithBody:body - completionHandler: ^(SWGOrder* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGStoreApi->placeOrder: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Place an order for a pet +[apiInstance placeOrderWithBody:body + completionHandler: ^(SWGOrder* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGStoreApi->placeOrder: %@", error); + } + }]; ``` ### Parameters diff --git a/samples/client/petstore/objc/docs/SWGUserApi.md b/samples/client/petstore/objc/docs/SWGUserApi.md index 4fe7a25bccf..c7a62f3b3c4 100644 --- a/samples/client/petstore/objc/docs/SWGUserApi.md +++ b/samples/client/petstore/objc/docs/SWGUserApi.md @@ -29,23 +29,15 @@ This can only be done by the logged in user. SWGUser* body = [[SWGUser alloc] init]; // Created user object (optional) -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Create user - [apiInstance createUserWithBody:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->createUser: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Create user +[apiInstance createUserWithBody:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->createUser: %@", error); + } + }]; ``` ### Parameters @@ -84,23 +76,15 @@ Creates list of users with given input array NSArray* body = @[[[SWGUser alloc] init]]; // List of user object (optional) -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Creates list of users with given input array - [apiInstance createUsersWithArrayInputWithBody:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->createUsersWithArrayInput: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Creates list of users with given input array +[apiInstance createUsersWithArrayInputWithBody:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->createUsersWithArrayInput: %@", error); + } + }]; ``` ### Parameters @@ -139,23 +123,15 @@ Creates list of users with given input array NSArray* body = @[[[SWGUser alloc] init]]; // List of user object (optional) -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Creates list of users with given input array - [apiInstance createUsersWithListInputWithBody:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->createUsersWithListInput: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Creates list of users with given input array +[apiInstance createUsersWithListInputWithBody:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->createUsersWithListInput: %@", error); + } + }]; ``` ### Parameters @@ -194,23 +170,15 @@ This can only be done by the logged in user. NSString* username = @"username_example"; // The name that needs to be deleted -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Delete user - [apiInstance deleteUserWithUsername:username - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->deleteUser: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Delete user +[apiInstance deleteUserWithUsername:username + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->deleteUser: %@", error); + } + }]; ``` ### Parameters @@ -249,26 +217,18 @@ Get user by user name NSString* username = @"username_example"; // The name that needs to be fetched. Use user1 for testing. -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Get user by user name - [apiInstance getUserByNameWithUsername:username - completionHandler: ^(SWGUser* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->getUserByName: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Get user by user name +[apiInstance getUserByNameWithUsername:username + completionHandler: ^(SWGUser* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGUserApi->getUserByName: %@", error); + } + }]; ``` ### Parameters @@ -309,27 +269,19 @@ Logs user into the system NSString* username = @"username_example"; // The user name for login (optional) NSString* password = @"password_example"; // The password for login in clear text (optional) -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Logs user into the system - [apiInstance loginUserWithUsername:username - password:password - completionHandler: ^(NSString* output, NSError* error) { - if (output) { - NSLog(@"%@", output); - } - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->loginUser: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Logs user into the system +[apiInstance loginUserWithUsername:username + password:password + completionHandler: ^(NSString* output, NSError* error) { + if (output) { + NSLog(@"%@", output); + } + if (error) { + NSLog(@"Error calling SWGUserApi->loginUser: %@", error); + } + }]; ``` ### Parameters @@ -368,23 +320,15 @@ Logs out current logged in user session ```objc -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Logs out current logged in user session - [apiInstance logoutUserWithCompletionHandler: - ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->logoutUser: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Logs out current logged in user session +[apiInstance logoutUserWithCompletionHandler: + ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->logoutUser: %@", error); + } + }]; ``` ### Parameters @@ -422,24 +366,16 @@ This can only be done by the logged in user. NSString* username = @"username_example"; // name that need to be deleted SWGUser* body = [[SWGUser alloc] init]; // Updated user object (optional) -@try -{ - SWGUserApi *apiInstance = [[SWGUserApi alloc] init]; +SWGUserApi*apiInstance = [[SWGUserApi alloc] init]; - // Updated user - [apiInstance updateUserWithUsername:username - body:body - completionHandler: ^(NSError* error) { - if (error) { - NSLog(@"Error: %@", error); - } - }]; -} -@catch (NSException *exception) -{ - NSLog(@"Exception when calling SWGUserApi->updateUser: %@ ", exception.name); - NSLog(@"Reason: %@ ", exception.reason); -} +// Updated user +[apiInstance updateUserWithUsername:username + body:body + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGUserApi->updateUser: %@", error); + } + }]; ``` ### Parameters diff --git a/samples/client/petstore/perl/.swagger-codegen-ignore b/samples/client/petstore/perl/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/perl/.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 +# Thsi 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/perl/LICENSE b/samples/client/petstore/perl/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/perl/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index a4c5c47558a..5e12d98f02f 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -2,7 +2,7 @@ WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +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 @@ -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 date: 2016-04-13T22:41:41.133+08:00 +- Build date: 2016-06-10T22:39:40.931+08:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose @@ -223,6 +223,7 @@ Each of these calls returns a hashref with various useful pieces of information. To load the API packages: ```perl +use WWW::SwaggerClient::FakeApi; use WWW::SwaggerClient::PetApi; use WWW::SwaggerClient::StoreApi; use WWW::SwaggerClient::UserApi; @@ -231,17 +232,24 @@ use WWW::SwaggerClient::UserApi; To load the models: ```perl +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::AnimalFarm; use WWW::SwaggerClient::Object::ApiResponse; +use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumClass; +use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::Order; use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; @@ -256,22 +264,30 @@ use lib 'lib'; use strict; use warnings; # load the API package +use WWW::SwaggerClient::FakeApi; use WWW::SwaggerClient::PetApi; use WWW::SwaggerClient::StoreApi; use WWW::SwaggerClient::UserApi; # load the models +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::AnimalFarm; use WWW::SwaggerClient::Object::ApiResponse; +use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumClass; +use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::Order; use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; @@ -279,17 +295,25 @@ use WWW::SwaggerClient::Object::User; # for displaying the API response data use Data::Dumper; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store +my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $number = 3.4; # Number | None +my $double = 1.2; # double | None +my $string = 'string_example'; # string | None +my $byte = 'B'; # string | None +my $integer = 56; # int | None +my $int32 = 56; # int | None +my $int64 = 789; # int | None +my $float = 3.4; # double | 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 eval { - $api_instance->add_pet(body => $body); + $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); }; if ($@) { - warn "Exception when calling PetApi->add_pet: $@\n"; + warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; } ``` @@ -300,6 +324,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -323,17 +348,24 @@ Class | Method | HTTP request | Description # DOCUMENTATION FOR MODELS + - [WWW::SwaggerClient::Object::AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Animal](docs/Animal.md) + - [WWW::SwaggerClient::Object::AnimalFarm](docs/AnimalFarm.md) - [WWW::SwaggerClient::Object::ApiResponse](docs/ApiResponse.md) + - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) + - [WWW::SwaggerClient::Object::EnumClass](docs/EnumClass.md) + - [WWW::SwaggerClient::Object::EnumTest](docs/EnumTest.md) - [WWW::SwaggerClient::Object::FormatTest](docs/FormatTest.md) + - [WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Model200Response](docs/Model200Response.md) - [WWW::SwaggerClient::Object::ModelReturn](docs/ModelReturn.md) - [WWW::SwaggerClient::Object::Name](docs/Name.md) - [WWW::SwaggerClient::Object::Order](docs/Order.md) - [WWW::SwaggerClient::Object::Pet](docs/Pet.md) + - [WWW::SwaggerClient::Object::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [WWW::SwaggerClient::Object::SpecialModelName](docs/SpecialModelName.md) - [WWW::SwaggerClient::Object::Tag](docs/Tag.md) - [WWW::SwaggerClient::Object::User](docs/User.md) @@ -351,7 +383,7 @@ Class | Method | HTTP request | Description - **Type**: OAuth - **Flow**: implicit -- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - **write:pets**: modify pets in your account - **read:pets**: read your pets diff --git a/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md b/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ab590075a14 --- /dev/null +++ b/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::AdditionalPropertiesClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_property** | **HASH[string,string]** | | [optional] +**map_of_map_property** | **HASH[string,HASH[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/client/petstore/perl/docs/Animal.md b/samples/client/petstore/perl/docs/Animal.md index d243a90905d..38cc8ac0690 100644 --- a/samples/client/petstore/perl/docs/Animal.md +++ b/samples/client/petstore/perl/docs/Animal.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Animal; 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/client/petstore/perl/docs/AnimalFarm.md b/samples/client/petstore/perl/docs/AnimalFarm.md new file mode 100644 index 00000000000..18848e9c0ba --- /dev/null +++ b/samples/client/petstore/perl/docs/AnimalFarm.md @@ -0,0 +1,14 @@ +# WWW::SwaggerClient::Object::AnimalFarm + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/client/petstore/perl/docs/ArrayTest.md b/samples/client/petstore/perl/docs/ArrayTest.md new file mode 100644 index 00000000000..635c26a893a --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayTest.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::ArrayTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayTest; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_of_string** | **ARRAY[string]** | | [optional] +**array_array_of_integer** | **ARRAY[ARRAY[int]]** | | [optional] +**array_array_of_model** | **ARRAY[ARRAY[ReadOnlyFirst]]** | | [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/Cat.md b/samples/client/petstore/perl/docs/Cat.md index 978e4202394..0539f73e502 100644 --- a/samples/client/petstore/perl/docs/Cat.md +++ b/samples/client/petstore/perl/docs/Cat.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Cat; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] **declawed** | **boolean** | | [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/Dog.md b/samples/client/petstore/perl/docs/Dog.md index 16e399c3aae..16d3972d2b5 100644 --- a/samples/client/petstore/perl/docs/Dog.md +++ b/samples/client/petstore/perl/docs/Dog.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Dog; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] **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/client/petstore/perl/docs/EnumClass.md b/samples/client/petstore/perl/docs/EnumClass.md new file mode 100644 index 00000000000..c4e40dbf06b --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumClass.md @@ -0,0 +1,14 @@ +# WWW::SwaggerClient::Object::EnumClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/client/petstore/perl/docs/EnumTest.md b/samples/client/petstore/perl/docs/EnumTest.md new file mode 100644 index 00000000000..0c3416150e1 --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumTest.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::EnumTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::EnumTest; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [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/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md new file mode 100644 index 00000000000..94c13795a10 --- /dev/null +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -0,0 +1,79 @@ +# WWW::SwaggerClient::FakeApi + +## Load the API package +```perl +use WWW::SwaggerClient::Object::FakeApi; +``` + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + +# **test_endpoint_parameters** +> test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $number = 3.4; # Number | None +my $double = 1.2; # double | None +my $string = 'string_example'; # string | None +my $byte = 'B'; # string | None +my $integer = 56; # int | None +my $int32 = 56; # int | None +my $int64 = 789; # int | None +my $float = 3.4; # double | 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 + +eval { + $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); +}; +if ($@) { + warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Number**| None | + **double** | **double**| None | + **string** | **string**| None | + **byte** | **string**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **double**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **DateTime**| None | [optional] + **date_time** | **DateTime**| None | [optional] + **password** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### 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 + +[[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/FormatTest.md b/samples/client/petstore/perl/docs/FormatTest.md index 60cd71ac61f..9ba3aeaf17b 100644 --- a/samples/client/petstore/perl/docs/FormatTest.md +++ b/samples/client/petstore/perl/docs/FormatTest.md @@ -15,11 +15,12 @@ Name | Type | Description | Notes **float** | **double** | | [optional] **double** | **double** | | [optional] **string** | **string** | | [optional] -**byte** | **string** | | [optional] +**byte** | **string** | | **binary** | **string** | | [optional] -**date** | **DateTime** | | [optional] +**date** | **DateTime** | | **date_time** | **DateTime** | | [optional] -**password** | **string** | | [optional] +**uuid** | [**UUID**](UUID.md) | | [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/client/petstore/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..28bf101a8a1 --- /dev/null +++ b/samples/client/petstore/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | [**UUID**](UUID.md) | | [optional] +**date_time** | **DateTime** | | [optional] +**map** | [**HASH[string,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/client/petstore/perl/docs/Name.md b/samples/client/petstore/perl/docs/Name.md index 7109642a08b..1407fb99bcb 100644 --- a/samples/client/petstore/perl/docs/Name.md +++ b/samples/client/petstore/perl/docs/Name.md @@ -10,6 +10,8 @@ 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/client/petstore/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index 829dc3a08ef..c2f4e2ce4ee 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -10,13 +10,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -[**add_pet_using_byte_array**](PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store [**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet [**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status [**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags [**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -[**get_pet_by_id_in_object**](PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -[**pet_pet_idtesting_byte_arraytrue_get**](PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' [**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet [**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data [**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image @@ -51,7 +48,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -64,53 +61,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml - -[[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) - -# **add_pet_using_byte_array** -> add_pet_using_byte_array(body => $body) - -Fake endpoint to test byte array in body parameter for adding a new pet to the store - - - -### Example -```perl -use Data::Dumper; - -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $body = WWW::SwaggerClient::Object::string->new(); # string | Pet object in the form of byte array - -eval { - $api_instance->add_pet_using_byte_array(body => $body); -}; -if ($@) { - warn "Exception when calling PetApi->add_pet_using_byte_array: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **string**| Pet object in the form of byte array | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **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) @@ -158,7 +109,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -177,7 +128,7 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $status = (); # ARRAY[string] | Status values that need to be considered for query +my $status = (); # ARRAY[string] | Status values that need to be considered for filter eval { my $result = $api_instance->find_pets_by_status(status => $status); @@ -192,7 +143,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**ARRAY[string]**](string.md)| Status values that need to be considered for query | [optional] [default to available] + **status** | [**ARRAY[string]**](string.md)| Status values that need to be considered for filter | ### Return type @@ -205,7 +156,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -214,7 +165,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```perl @@ -239,7 +190,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**ARRAY[string]**](string.md)| Tags to filter by | [optional] + **tags** | [**ARRAY[string]**](string.md)| Tags to filter by | ### Return type @@ -252,7 +203,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -261,7 +212,7 @@ Name | Type | Description | Notes Find pet by ID -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions +Returns a single pet ### Example ```perl @@ -271,11 +222,9 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; # uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched +my $pet_id = 789; # int | ID of pet to return eval { my $result = $api_instance->get_pet_by_id(pet_id => $pet_id); @@ -290,7 +239,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | + **pet_id** | **int**| ID of pet to return | ### Return type @@ -298,114 +247,12 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[api_key](../README.md#api_key) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[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) - -# **get_pet_by_id_in_object** -> InlineResponse200 get_pet_by_id_in_object(pet_id => $pet_id) - -Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched - -eval { - my $result = $api_instance->get_pet_by_id_in_object(pet_id => $pet_id); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling PetApi->get_pet_by_id_in_object: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | - -### Return type - -[**InlineResponse200**](InlineResponse200.md) - -### Authorization - -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[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) - -# **pet_pet_idtesting_byte_arraytrue_get** -> string pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id) - -Fake endpoint to test byte array return by 'Find pet by ID' - -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched - -eval { - my $result = $api_instance->pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling PetApi->pet_pet_idtesting_byte_arraytrue_get: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | - -### Return type - -**string** - -### Authorization - -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -438,7 +285,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -451,7 +298,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **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) @@ -470,7 +317,7 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 'pet_id_example'; # string | ID of pet that needs to be updated +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 @@ -486,7 +333,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **string**| ID of pet that needs to be updated | + **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] @@ -501,12 +348,12 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: application/json, application/xml + - **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) # **upload_file** -> upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file) +> ApiResponse upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file) uploads an image @@ -525,7 +372,8 @@ my $additional_metadata = 'additional_metadata_example'; # string | Additional d my $file = '/path/to/file.txt'; # File | file to upload eval { - $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); + my $result = $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); + print Dumper($result); }; if ($@) { warn "Exception when calling PetApi->upload_file: $@\n"; @@ -542,7 +390,7 @@ Name | Type | Description | Notes ### Return type -void (empty response body) +[**ApiResponse**](ApiResponse.md) ### Authorization @@ -551,7 +399,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: multipart/form-data - - **Accept**: application/json, application/xml + - **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/client/petstore/perl/docs/ReadOnlyFirst.md b/samples/client/petstore/perl/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..51f643016bc --- /dev/null +++ b/samples/client/petstore/perl/docs/ReadOnlyFirst.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::ReadOnlyFirst + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index c5eb55a3f12..f0681b47167 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -10,9 +10,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -[**find_orders_by_status**](StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status [**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -[**get_inventory_in_object**](StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' [**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID [**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet @@ -56,60 +54,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[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) - -# **find_orders_by_status** -> ARRAY[Order] find_orders_by_status(status => $status) - -Finds orders by status - -A single status value can be provided as a string - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: test_api_client_id -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; -# Configure API key authorization: test_api_client_secret -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; - -my $api_instance = WWW::SwaggerClient::StoreApi->new(); -my $status = 'status_example'; # string | Status value that needs to be considered for query - -eval { - my $result = $api_instance->find_orders_by_status(status => $status); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling StoreApi->find_orders_by_status: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | **string**| Status value that needs to be considered for query | [optional] [default to placed] - -### Return type - -[**ARRAY[Order]**](Order.md) - -### Authorization - -[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -154,52 +99,7 @@ This endpoint does not need any parameter. ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[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) - -# **get_inventory_in_object** -> object get_inventory_in_object() - -Fake endpoint to test arbitrary object return by 'Get inventory' - -Returns an arbitrary object which is actually a map of status codes to quantities - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; - -my $api_instance = WWW::SwaggerClient::StoreApi->new(); - -eval { - my $result = $api_instance->get_inventory_in_object(); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling StoreApi->get_inventory_in_object: $@\n"; -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -**object** - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -214,17 +114,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```perl use Data::Dumper; -# Configure API key authorization: test_api_key_header -$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_header'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_header'} = "Bearer"; -# Configure API key authorization: test_api_key_query -$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_query'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_query'} = "Bearer"; - my $api_instance = WWW::SwaggerClient::StoreApi->new(); -my $order_id = 'order_id_example'; # string | ID of pet that needs to be fetched +my $order_id = 789; # int | ID of pet that needs to be fetched eval { my $result = $api_instance->get_order_by_id(order_id => $order_id); @@ -239,7 +130,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order_id** | **string**| ID of pet that needs to be fetched | + **order_id** | **int**| ID of pet that needs to be fetched | ### Return type @@ -247,12 +138,12 @@ Name | Type | Description | Notes ### Authorization -[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) +No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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) @@ -267,15 +158,6 @@ Place an order for a pet ```perl use Data::Dumper; -# Configure API key authorization: test_api_client_id -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; -# Configure API key authorization: test_api_client_secret -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; - my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet @@ -292,7 +174,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + **body** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -300,12 +182,12 @@ Name | Type | Description | Notes ### Authorization -[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) +No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **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/git_push.sh b/samples/client/petstore/perl/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/perl/git_push.sh +++ b/samples/client/petstore/perl/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + 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="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 3dfa6633ee5..9b990cd26b0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::ApiClient; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm index 0ffd5498420..daf6735e804 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::ApiFactory; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index 150db4cfac2..e99ca4df5fa 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Configuration; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm new file mode 100644 index 00000000000..905690756bb --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -0,0 +1,264 @@ +=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 + +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. + +=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::FakeApi; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + +use WWW::SwaggerClient::ApiClient; +use WWW::SwaggerClient::Configuration; + +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + +sub new { + my $class = shift; + my (%self) = ( + 'api_client' => WWW::SwaggerClient::ApiClient->instance, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + +# +# test_endpoint_parameters +# +# Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +# +# @param Number $number None (required) +# @param double $double None (required) +# @param string $string None (required) +# @param string $byte None (required) +# @param int $integer None (optional) +# @param int $int32 None (optional) +# @param int $int64 None (optional) +# @param double $float None (optional) +# @param string $binary None (optional) +# @param DateTime $date None (optional) +# @param DateTime $date_time None (optional) +# @param string $password None (optional) +{ + my $params = { + 'number' => { + data_type => 'Number', + description => 'None', + required => '1', + }, + 'double' => { + data_type => 'double', + description => 'None', + required => '1', + }, + 'string' => { + data_type => 'string', + description => 'None', + required => '1', + }, + 'byte' => { + data_type => 'string', + description => 'None', + required => '1', + }, + 'integer' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'int32' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'int64' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'float' => { + data_type => 'double', + description => 'None', + required => '0', + }, + 'binary' => { + data_type => 'string', + description => 'None', + required => '0', + }, + 'date' => { + data_type => 'DateTime', + description => 'None', + required => '0', + }, + 'date_time' => { + data_type => 'DateTime', + description => 'None', + required => '0', + }, + 'password' => { + data_type => 'string', + description => 'None', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ test_endpoint_parameters } = { + summary => 'Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_endpoint_parameters { + my ($self, %args) = @_; + + # verify the required parameter 'number' is set + unless (exists $args{'number'}) { + croak("Missing the required parameter 'number' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'double' is set + unless (exists $args{'double'}) { + croak("Missing the required parameter 'double' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'string' is set + unless (exists $args{'string'}) { + croak("Missing the required parameter 'string' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'byte' is set + unless (exists $args{'byte'}) { + croak("Missing the required parameter 'byte' when calling test_endpoint_parameters"); + } + + # parse inputs + my $_resource_path = '/fake'; + $_resource_path =~ s/{format}/json/; # default format to json + + 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('application/xml; charset=utf-8', 'application/json; charset=utf-8'); + 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'); + + # form params + if ( exists $args{'integer'} ) { + $form_params->{'integer'} = $self->{api_client}->to_form_value($args{'integer'}); + } + + # form params + if ( exists $args{'int32'} ) { + $form_params->{'int32'} = $self->{api_client}->to_form_value($args{'int32'}); + } + + # form params + if ( exists $args{'int64'} ) { + $form_params->{'int64'} = $self->{api_client}->to_form_value($args{'int64'}); + } + + # form params + if ( exists $args{'number'} ) { + $form_params->{'number'} = $self->{api_client}->to_form_value($args{'number'}); + } + + # form params + if ( exists $args{'float'} ) { + $form_params->{'float'} = $self->{api_client}->to_form_value($args{'float'}); + } + + # form params + if ( exists $args{'double'} ) { + $form_params->{'double'} = $self->{api_client}->to_form_value($args{'double'}); + } + + # form params + if ( exists $args{'string'} ) { + $form_params->{'string'} = $self->{api_client}->to_form_value($args{'string'}); + } + + # form params + if ( exists $args{'byte'} ) { + $form_params->{'byte'} = $self->{api_client}->to_form_value($args{'byte'}); + } + + # form params + if ( exists $args{'binary'} ) { + $form_params->{'binary'} = $self->{api_client}->to_form_value($args{'binary'}); + } + + # form params + if ( exists $args{'date'} ) { + $form_params->{'date'} = $self->{api_client}->to_form_value($args{'date'}); + } + + # form params + if ( exists $args{'date_time'} ) { + $form_params->{'dateTime'} = $self->{api_client}->to_form_value($args{'date_time'}); + } + + # form params + if ( exists $args{'password'} ) { + $form_params->{'password'} = $self->{api_client}->to_form_value($args{'password'}); + } + + 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; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm new file mode 100644 index 00000000000..76c1f19543c --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm @@ -0,0 +1,198 @@ +=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 + +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. + +=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::AdditionalPropertiesClass; + +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 + +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. + +=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 => 'AdditionalPropertiesClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'map_property' => { + datatype => 'HASH[string,string]', + base_name => 'map_property', + description => '', + format => '', + read_only => '', + }, + 'map_of_map_property' => { + datatype => 'HASH[string,HASH[string,string]]', + base_name => 'map_of_map_property', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'map_property' => 'HASH[string,string]', + 'map_of_map_property' => 'HASH[string,HASH[string,string]]' +} ); + +__PACKAGE__->attribute_map( { + 'map_property' => 'map_property', + 'map_of_map_property' => 'map_of_map_property' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm index eb1b10034e9..443701ce326 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Animal; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); @@ -110,14 +173,23 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { - 'class_name' => 'string' + 'class_name' => 'string', + 'color' => 'string' } ); __PACKAGE__->attribute_map( { - 'class_name' => 'className' + 'class_name' => 'className', + 'color' => 'color' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm new file mode 100644 index 00000000000..32424c88e52 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm @@ -0,0 +1,182 @@ +=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 + +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. + +=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::AnimalFarm; + +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 + +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. + +=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 => 'AnimalFarm', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ +}); + +__PACKAGE__->swagger_types( { + +} ); + +__PACKAGE__->attribute_map( { + +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm index 9203da585b7..d1ee5704703 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::ApiResponse; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm new file mode 100644 index 00000000000..fa169ba4674 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm @@ -0,0 +1,207 @@ +=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 + +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. + +=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::ArrayTest; + +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 + +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. + +=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 => 'ArrayTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_of_string' => { + datatype => 'ARRAY[string]', + base_name => 'array_of_string', + description => '', + format => '', + read_only => '', + }, + 'array_array_of_integer' => { + datatype => 'ARRAY[ARRAY[int]]', + base_name => 'array_array_of_integer', + description => '', + format => '', + read_only => '', + }, + 'array_array_of_model' => { + datatype => 'ARRAY[ARRAY[ReadOnlyFirst]]', + base_name => 'array_array_of_model', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_of_string' => 'ARRAY[string]', + 'array_array_of_integer' => 'ARRAY[ARRAY[int]]', + 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]' +} ); + +__PACKAGE__->attribute_map( { + 'array_of_string' => 'array_of_string', + 'array_array_of_integer' => 'array_array_of_integer', + 'array_array_of_model' => 'array_array_of_model' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm index 41e542afd9f..16d524d0c2d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Cat; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); @@ -110,6 +173,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, 'declawed' => { datatype => 'boolean', base_name => 'declawed', @@ -121,11 +191,13 @@ __PACKAGE__->method_documentation({ __PACKAGE__->swagger_types( { 'class_name' => 'string', + 'color' => 'string', 'declawed' => 'boolean' } ); __PACKAGE__->attribute_map( { 'class_name' => 'className', + 'color' => 'color', 'declawed' => 'declawed' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 2d49d6a99b8..30b83ba1e65 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Category; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm index 6ac41e2a9ff..4964f4dd97e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Dog; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); @@ -110,6 +173,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, 'breed' => { datatype => 'string', base_name => 'breed', @@ -121,11 +191,13 @@ __PACKAGE__->method_documentation({ __PACKAGE__->swagger_types( { 'class_name' => 'string', + 'color' => 'string', 'breed' => 'string' } ); __PACKAGE__->attribute_map( { 'class_name' => 'className', + 'color' => 'color', 'breed' => 'breed' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm new file mode 100644 index 00000000000..89ad6d8cc71 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm @@ -0,0 +1,182 @@ +=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 + +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. + +=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::EnumClass; + +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 + +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. + +=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 => 'EnumClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ +}); + +__PACKAGE__->swagger_types( { + +} ); + +__PACKAGE__->attribute_map( { + +} ); + +__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 new file mode 100644 index 00000000000..d1806d2b803 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm @@ -0,0 +1,207 @@ +=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 + +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. + +=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::EnumTest; + +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 + +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. + +=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 => 'EnumTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'enum_string' => { + datatype => 'string', + base_name => 'enum_string', + description => '', + format => '', + read_only => '', + }, + 'enum_integer' => { + datatype => 'int', + base_name => 'enum_integer', + description => '', + format => '', + read_only => '', + }, + 'enum_number' => { + datatype => 'double', + base_name => 'enum_number', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'enum_string' => 'string', + 'enum_integer' => 'int', + 'enum_number' => 'double' +} ); + +__PACKAGE__->attribute_map( { + 'enum_string' => 'enum_string', + 'enum_integer' => 'enum_integer', + 'enum_number' => 'enum_number' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; 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 725c290b11d..c5779fbe5b9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::FormatTest; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); @@ -180,6 +243,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'uuid' => { + datatype => 'UUID', + base_name => 'uuid', + description => '', + format => '', + read_only => '', + }, 'password' => { datatype => 'string', base_name => 'password', @@ -201,6 +271,7 @@ __PACKAGE__->swagger_types( { 'binary' => 'string', 'date' => 'DateTime', 'date_time' => 'DateTime', + 'uuid' => 'UUID', 'password' => 'string' } ); @@ -216,6 +287,7 @@ __PACKAGE__->attribute_map( { 'binary' => 'binary', 'date' => 'date', 'date_time' => 'dateTime', + 'uuid' => 'uuid', 'password' => 'password' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm new file mode 100644 index 00000000000..50a42581c27 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm @@ -0,0 +1,207 @@ +=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 + +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. + +=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::MixedPropertiesAndAdditionalPropertiesClass; + +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 + +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. + +=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 => 'MixedPropertiesAndAdditionalPropertiesClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'uuid' => { + datatype => 'UUID', + base_name => 'uuid', + description => '', + format => '', + read_only => '', + }, + 'date_time' => { + datatype => 'DateTime', + base_name => 'dateTime', + description => '', + format => '', + read_only => '', + }, + 'map' => { + datatype => 'HASH[string,Animal]', + base_name => 'map', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'uuid' => 'UUID', + 'date_time' => 'DateTime', + 'map' => 'HASH[string,Animal]' +} ); + +__PACKAGE__->attribute_map( { + 'uuid' => 'uuid', + 'date_time' => 'dateTime', + 'map' => 'map' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm index d64f9497753..7bb7cce1a6e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Model200Response; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing model name starting with number # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm index 682d26d7436..09af2a0884b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::ModelReturn; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing reserved words # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm index b5a58e0d5fa..50d950fb29a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Name; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing model name same as property name # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# 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 + +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. + +=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' => {}); @@ -117,16 +180,34 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'property' => { + datatype => 'string', + base_name => 'property', + description => '', + format => '', + read_only => '', + }, + '_123_number' => { + datatype => 'int', + base_name => '123Number', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { 'name' => 'int', - 'snake_case' => 'int' + 'snake_case' => 'int', + 'property' => 'string', + '_123_number' => 'int' } ); __PACKAGE__->attribute_map( { 'name' => 'name', - 'snake_case' => 'snake_case' + 'snake_case' => 'snake_case', + 'property' => 'property', + '_123_number' => '123Number' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 6590dba2293..c8fef7564cb 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Order; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index 50334ab062a..e63f9a4a75a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Pet; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm new file mode 100644 index 00000000000..45141fdd1ca --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm @@ -0,0 +1,198 @@ +=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 + +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. + +=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::ReadOnlyFirst; + +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 + +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. + +=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 => 'ReadOnlyFirst', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'bar' => { + datatype => 'string', + base_name => 'bar', + description => '', + format => '', + read_only => '', + }, + 'baz' => { + datatype => 'string', + base_name => 'baz', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'bar' => 'string', + 'baz' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'bar' => 'bar', + 'baz' => 'baz' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm index 5666b39c07b..e051fd994b6 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index b60ccc4a005..250a23c6870 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Tag; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 8b0555d8aaa..b5c5fcc6e7e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::User; require 5.6.0; @@ -17,9 +48,41 @@ 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. +# 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 + +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. + +=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' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index fd1b4092302..ecb7d70bf5b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=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 + +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. + +=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::PetApi; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index e72b12a22b8..cc146cb1890 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Role; use utf8; @@ -37,7 +68,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-04-13T22:41:41.133+08:00', + generated_date => '2016-06-10T22:39:40.931+08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -103,7 +134,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2016-04-13T22:41:41.133+08:00 +=item Build date: 2016-06-10T22:39:40.931+08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm index d57c96c1798..55e8af85228 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm @@ -1,3 +1,34 @@ +=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 + +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. + +=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::Role::AutoDoc; use List::MoreUtils qw(uniq); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 16a4f13cb1e..f29c64ec1a1 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=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 + +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. + +=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::StoreApi; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 75f56f56293..b6b5252e93e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=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 + +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. + +=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::UserApi; diff --git a/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t b/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t new file mode 100644 index 00000000000..03aa037413f --- /dev/null +++ b/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::AdditionalPropertiesClass'); + +my $instance = WWW::SwaggerClient::Object::AdditionalPropertiesClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::AdditionalPropertiesClass'); + diff --git a/samples/client/petstore/perl/t/AnimalFarmTest.t b/samples/client/petstore/perl/t/AnimalFarmTest.t new file mode 100644 index 00000000000..4c795259eec --- /dev/null +++ b/samples/client/petstore/perl/t/AnimalFarmTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::AnimalFarm'); + +my $instance = WWW::SwaggerClient::Object::AnimalFarm->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::AnimalFarm'); + diff --git a/samples/client/petstore/perl/t/ArrayTestTest.t b/samples/client/petstore/perl/t/ArrayTestTest.t new file mode 100644 index 00000000000..3873ad59787 --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayTestTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayTest'); + +my $instance = WWW::SwaggerClient::Object::ArrayTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayTest'); + diff --git a/samples/client/petstore/perl/t/EnumClassTest.t b/samples/client/petstore/perl/t/EnumClassTest.t new file mode 100644 index 00000000000..c1843e3bab4 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumClass'); + +my $instance = WWW::SwaggerClient::Object::EnumClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumClass'); + diff --git a/samples/client/petstore/perl/t/EnumTestTest.t b/samples/client/petstore/perl/t/EnumTestTest.t new file mode 100644 index 00000000000..6a72a3da4f7 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumTestTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumTest'); + +my $instance = WWW::SwaggerClient::Object::EnumTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumTest'); + diff --git a/samples/client/petstore/perl/t/FakeApiTest.t b/samples/client/petstore/perl/t/FakeApiTest.t new file mode 100644 index 00000000000..e57a0e5a048 --- /dev/null +++ b/samples/client/petstore/perl/t/FakeApiTest.t @@ -0,0 +1,52 @@ +# +# Copyright 2016 SmartBear Software +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test case below to test the API endpoints. +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::FakeApi'); + +my $api = WWW::SwaggerClient::FakeApi->new(); +isa_ok($api, 'WWW::SwaggerClient::FakeApi'); + +# +# test_endpoint_parameters test +# +{ + my $number = undef; # replace NULL with a proper value + my $double = undef; # replace NULL with a proper value + my $string = undef; # replace NULL with a proper value + my $byte = undef; # replace NULL with a proper value + my $integer = undef; # replace NULL with a proper value + my $int32 = undef; # replace NULL with a proper value + my $int64 = undef; # replace NULL with a proper value + my $float = undef; # replace NULL with a proper value + my $binary = undef; # replace NULL with a proper value + my $date = undef; # replace NULL with a proper value + my $date_time = undef; # replace NULL with a proper value + my $password = undef; # replace NULL with a proper value + my $result = $api->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); +} + + +1; diff --git a/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t b/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t new file mode 100644 index 00000000000..b6f764e8210 --- /dev/null +++ b/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass'); + +my $instance = WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass'); + diff --git a/samples/client/petstore/perl/t/ReadOnlyFirstTest.t b/samples/client/petstore/perl/t/ReadOnlyFirstTest.t new file mode 100644 index 00000000000..9c35358bee1 --- /dev/null +++ b/samples/client/petstore/perl/t/ReadOnlyFirstTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ReadOnlyFirst'); + +my $instance = WWW::SwaggerClient::Object::ReadOnlyFirst->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ReadOnlyFirst'); + diff --git a/samples/client/petstore/php/.swagger-codegen-ignore b/samples/client/petstore/php/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/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 +# Thsi 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/php/SwaggerClient-php/LICENSE b/samples/client/petstore/php/SwaggerClient-php/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index fe09a19fa93..8d69c7da9e4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -1,11 +1,11 @@ # SwaggerClient-php -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +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 -- Package version: 1.0.0 -- Build date: 2016-05-10T22:37:00.768+08:00 +- Package version: +- Build date: 2016-05-25T22:55:19.912+02:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -41,7 +41,7 @@ Download the files and include `autoload.php`: require_once('/path/to/SwaggerClient-php/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -75,7 +75,7 @@ $password = "password_example"; // string | None try { $api_instance->testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), "\n"; + echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } ?> @@ -87,59 +87,57 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testEndpointParameters**](docs/ApiFakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*PetApi* | [**addPet**](docs/ApiPetApi.md#addpet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/ApiPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/ApiPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/ApiPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/ApiPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/ApiPetApi.md#updatepet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/ApiPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/ApiPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/ApiStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/ApiStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/ApiStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/ApiStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/ApiUserApi.md#createuser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/ApiUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/ApiUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/ApiUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/ApiUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/ApiUserApi.md#loginuser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/ApiUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/ApiUserApi.md#updateuser) | **PUT** /user/{username} | Updated user +*FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*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/{orderId} | 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/{orderId} | 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 - - [Animal](docs/ModelAnimal.md) - - [AnimalFarm](docs/ModelAnimalFarm.md) - - [ApiResponse](docs/ModelApiResponse.md) - - [Cat](docs/ModelCat.md) - - [Category](docs/ModelCategory.md) - - [Dog](docs/ModelDog.md) - - [EnumClass](docs/ModelEnumClass.md) - - [EnumTest](docs/ModelEnumTest.md) - - [FormatTest](docs/ModelFormatTest.md) - - [Model200Response](docs/ModelModel200Response.md) - - [ModelReturn](docs/ModelModelReturn.md) - - [Name](docs/ModelName.md) - - [Order](docs/ModelOrder.md) - - [Pet](docs/ModelPet.md) - - [SpecialModelName](docs/ModelSpecialModelName.md) - - [Tag](docs/ModelTag.md) - - [User](docs/ModelUser.md) + - [AdditionalPropertiesClass](docs/Model/AdditionalPropertiesClass.md) + - [Animal](docs/Model/Animal.md) + - [AnimalFarm](docs/Model/AnimalFarm.md) + - [ApiResponse](docs/Model/ApiResponse.md) + - [ArrayTest](docs/Model/ArrayTest.md) + - [Cat](docs/Model/Cat.md) + - [Category](docs/Model/Category.md) + - [Dog](docs/Model/Dog.md) + - [EnumClass](docs/Model/EnumClass.md) + - [EnumTest](docs/Model/EnumTest.md) + - [FormatTest](docs/Model/FormatTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model/Model200Response.md) + - [ModelReturn](docs/Model/ModelReturn.md) + - [Name](docs/Model/Name.md) + - [Order](docs/Model/Order.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 - ## petstore_auth - **Type**: OAuth @@ -149,6 +147,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/autoload.php b/samples/client/petstore/php/SwaggerClient-php/autoload.php index acbd3968b23..de411ee498a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore/php/SwaggerClient-php/autoload.php @@ -1,14 +1,38 @@ testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -### Example +### Example ```php testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), "\n"; + echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -45,18 +45,18 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **float**| None | - **double** | **double**| None | - **string** | **string**| None | - **byte** | **string**| None | - **integer** | **int**| None | [optional] - **int32** | **int**| None | [optional] - **int64** | **int**| None | [optional] - **float** | **float**| None | [optional] - **binary** | **string**| None | [optional] - **date** | **\DateTime**| None | [optional] - **date_time** | **\DateTime**| None | [optional] - **password** | **string**| None | [optional] + **number** | **float**| None | + **double** | **double**| None | + **string** | **string**| None | + **byte** | **string**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **\DateTime**| None | [optional] + **date_time** | **\DateTime**| None | [optional] + **password** | **string**| None | [optional] ### Return type @@ -68,8 +68,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 -[[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) +[[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/docs/Api/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index bf119270a58..d99eea4c925 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->addPet($body); } catch (Exception $e) { - echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -44,7 +44,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -52,14 +52,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/json, application/xml - **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) +[[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) @@ -68,7 +68,7 @@ Deletes a pet -### Example +### Example ```php deletePet($pet_id, $api_key); } catch (Exception $e) { - echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -92,8 +92,8 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| Pet id to delete | - **api_key** | **string**| | [optional] + **pet_id** | **int**| Pet id to delete | + **api_key** | **string**| | [optional] ### Return type @@ -101,14 +101,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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) @@ -117,7 +117,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $status = array("status_example"); // string[] | Status values that need to be considered for filter -try { +try { $result = $api_instance->findPetsByStatus($status); print_r($result); } catch (Exception $e) { - echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -141,22 +141,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**string[]**](string.md)| Status values that need to be considered for filter | + **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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) @@ -165,7 +165,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $tags = array("tags_example"); // string[] | Tags to filter by -try { +try { $result = $api_instance->findPetsByTags($tags); print_r($result); } catch (Exception $e) { - echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -189,22 +189,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**string[]**](string.md)| Tags to filter by | + **tags** | [**string[]**](../Model/string.md)| Tags to filter by | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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) @@ -213,7 +213,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\PetApi(); $pet_id = 789; // int | ID of pet to return -try { +try { $result = $api_instance->getPetById($pet_id); print_r($result); } catch (Exception $e) { - echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -239,22 +239,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet to return | + **pet_id** | **int**| ID of pet to return | ### Return type -[**\Swagger\Client\Model\Pet**](Pet.md) +[**\Swagger\Client\Model\Pet**](../Model/Pet.md) ### Authorization -[api_key](../README.md#api_key) +[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) +[[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($body) @@ -263,7 +263,7 @@ Update an existing pet -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->updatePet($body); } catch (Exception $e) { - echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -286,7 +286,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -294,14 +294,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/json, application/xml - **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) +[[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) @@ -310,7 +310,7 @@ Updates a pet in the store with form data -### Example +### Example ```php updatePetWithForm($pet_id, $name, $status); } catch (Exception $e) { - echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -335,9 +335,9 @@ try { 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] + **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 @@ -345,14 +345,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - **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) +[[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) @@ -361,7 +361,7 @@ uploads an image -### Example +### Example ```php uploadFile($pet_id, $additional_metadata, $file); print_r($result); } catch (Exception $e) { - echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), "\n"; + echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -387,22 +387,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet to update | - **additional_metadata** | **string**| Additional data to pass to server | [optional] - **file** | **\SplFileObject**| file to upload | [optional] + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **string**| Additional data to pass to server | [optional] + **file** | **\SplFileObject**| file to upload | [optional] ### Return type -[**\Swagger\Client\Model\ApiResponse**](ApiResponse.md) +[**\Swagger\Client\Model\ApiResponse**](../Model/ApiResponse.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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/docs/Api/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md index 7040df371a4..4ec88f083c7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -17,7 +17,7 @@ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -### Example +### Example ```php deleteOrder($order_id); } catch (Exception $e) { - echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), "\n"; + echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -37,7 +37,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order_id** | **string**| ID of the order that needs to be deleted | + **order_id** | **string**| ID of the order that needs to be deleted | ### Return type @@ -52,7 +52,7 @@ No authorization required - **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) +[[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() @@ -61,7 +61,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\StoreApi(); -try { +try { $result = $api_instance->getInventory(); print_r($result); } catch (Exception $e) { - echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), "\n"; + echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -87,18 +87,18 @@ This endpoint does not need any parameter. ### Return type -[**map[string,int]**](map.md) +[**map[string,int]**](../Model/map.md) ### Authorization -[api_key](../README.md#api_key) +[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) +[[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) @@ -107,7 +107,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```php getOrderById($order_id); print_r($result); } catch (Exception $e) { - echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), "\n"; + echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -128,11 +128,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order_id** | **int**| ID of pet that needs to be fetched | + **order_id** | **int**| ID of pet that needs to be fetched | ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -143,7 +143,7 @@ No authorization required - **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) +[[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($body) @@ -152,7 +152,7 @@ Place an order for a pet -### Example +### Example ```php placeOrder($body); print_r($result); } catch (Exception $e) { - echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), "\n"; + echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -173,11 +173,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Order**](\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | + **body** | [**\Swagger\Client\Model\Order**](../Model/\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -188,5 +188,5 @@ No authorization required - **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) +[[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/docs/Api/UserApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md index 7f048a429e3..6296b872220 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```php createUser($body); } catch (Exception $e) { - echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -41,7 +41,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Created user object | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Created user object | ### Return type @@ -56,7 +56,7 @@ No authorization required - **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) +[[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($body) @@ -65,7 +65,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithArrayInput($body); } catch (Exception $e) { - echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -85,7 +85,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -100,7 +100,7 @@ No authorization required - **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) +[[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($body) @@ -109,7 +109,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithListInput($body); } catch (Exception $e) { - echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -129,7 +129,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -144,7 +144,7 @@ No authorization required - **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) +[[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) @@ -153,7 +153,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```php deleteUser($username); } catch (Exception $e) { - echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -173,7 +173,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be deleted | + **username** | **string**| The name that needs to be deleted | ### Return type @@ -188,7 +188,7 @@ No authorization required - **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) +[[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) @@ -197,19 +197,19 @@ Get user by user name -### Example +### Example ```php getUserByName($username); print_r($result); } catch (Exception $e) { - echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -218,11 +218,11 @@ try { 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 -[**\Swagger\Client\Model\User**](User.md) +[**\Swagger\Client\Model\User**](../Model/User.md) ### Authorization @@ -233,7 +233,7 @@ No authorization required - **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) +[[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) @@ -242,7 +242,7 @@ Logs user into the system -### Example +### Example ```php loginUser($username, $password); print_r($result); } catch (Exception $e) { - echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -264,8 +264,8 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The user name for login | - **password** | **string**| The password for login in clear text | + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | ### Return type @@ -280,7 +280,7 @@ No authorization required - **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) +[[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() @@ -289,17 +289,17 @@ Logs out current logged in user session -### Example +### Example ```php logoutUser(); } catch (Exception $e) { - echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -320,7 +320,7 @@ No authorization required - **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) +[[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, $body) @@ -329,7 +329,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```php updateUser($username, $body); } catch (Exception $e) { - echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), "\n"; + echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -350,8 +350,8 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| name that need to be deleted | - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Updated user object | + **username** | **string**| name that need to be deleted | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Updated user object | ### Return type @@ -366,5 +366,5 @@ No authorization required - **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) +[[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/go/go-petstore/docs/ApiResponse.md b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md similarity index 62% rename from samples/client/petstore/go/go-petstore/docs/ApiResponse.md rename to samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md index 3653b42ba24..9d351183422 100644 --- a/samples/client/petstore/go/go-petstore/docs/ApiResponse.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Code** | **int32** | | [optional] [default to null] -**Type_** | **string** | | [optional] [default to null] -**Message** | **string** | | [optional] [default to null] +**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/client/petstore/php/SwaggerClient-php/docs/Cat.md b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md new file mode 100644 index 00000000000..8d30565d014 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Category.md b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md new file mode 100644 index 00000000000..80aef312e5e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Dog.md b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md new file mode 100644 index 00000000000..3c04bdf4cf7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/EnumClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md new file mode 100644 index 00000000000..2ef9e6adaac --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [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/php/SwaggerClient-php/docs/FormatTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md new file mode 100644 index 00000000000..90531d28c40 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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** | **string** | | [optional] +**date** | [**\DateTime**](Date.md) | | +**date_time** | [**\DateTime**](\DateTime.md) | | [optional] +**uuid** | [**UUID**](UUID.md) | | [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/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..420ac6efe67 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/AdditionalPropertiesClass.md @@ -0,0 +1,9 @@ +# AdditionalPropertiesClass + +## 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/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md new file mode 100644 index 00000000000..9dcc2c97264 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ArrayTest.md @@ -0,0 +1,9 @@ +# ArrayTest + +## 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/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..c05cee84500 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **string** | | [optional] +**date_time** | [**\DateTime**](\DateTime.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/client/petstore/php/SwaggerClient-php/docs/Model/ReadOnlyFirst.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ReadOnlyFirst.md new file mode 100644 index 00000000000..90662a00cf3 --- /dev/null +++ b/samples/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/client/petstore/php/SwaggerClient-php/docs/Model200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md new file mode 100644 index 00000000000..e29747a87e7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md @@ -0,0 +1,10 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**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/php/SwaggerClient-php/docs/ModelReturn.md b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md new file mode 100644 index 00000000000..9adb62e1e12 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Name.md b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md new file mode 100644 index 00000000000..4565647e1ef --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Order.md b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md new file mode 100644 index 00000000000..ddae5cc2b57 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Pet.md b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md new file mode 100644 index 00000000000..4525fe7d776 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md new file mode 100644 index 00000000000..022ee19169c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/Tag.md b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md new file mode 100644 index 00000000000..15ec3e0a91d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/docs/User.md b/samples/client/petstore/php/SwaggerClient-php/docs/User.md new file mode 100644 index 00000000000..ff278fd4889 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/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/client/petstore/php/SwaggerClient-php/git_push.sh b/samples/client/petstore/php/SwaggerClient-php/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/git_push.sh +++ b/samples/client/petstore/php/SwaggerClient-php/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/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 5620c82fdcd..d68bf418a00 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -9,25 +9,32 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +59,41 @@ class FakeApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return FakeApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,11 +101,11 @@ class FakeApi $this->apiClient = $apiClient; return $this; } - + /** - * testEndpointParameters + * Operation testEndpointParameters * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트. * * @param float $number None (required) * @param double $double None (required) @@ -107,20 +119,21 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function testEndpointParameters($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) { - list($response) = $this->testEndpointParametersWithHttpInfo ($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); - return $response; + list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + return $response; } /** - * testEndpointParametersWithHttpInfo + * Operation testEndpointParametersWithHttpInfo * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트. * * @param float $number None (required) * @param double $double None (required) @@ -134,6 +147,7 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,19 +216,19 @@ class FakeApi throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - + // parse inputs $resourcePath = "/fake"; $httpBody = ''; $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml; charset=utf-8', 'application/json; charset=utf-8')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/xml; charset=utf-8','application/json; charset=utf-8')); + @@ -259,7 +273,7 @@ class FakeApi $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -269,16 +283,17 @@ class FakeApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 4ab1529c7c0..9cca7063a53 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -9,25 +9,32 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +59,41 @@ class PetApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return PetApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +101,31 @@ class PetApi $this->apiClient = $apiClient; return $this; } - + /** - * addPet + * Operation addPet * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPet($body) { - list($response) = $this->addPetWithHttpInfo ($body); - return $response; + list($response) = $this->addPetWithHttpInfo($body); + return $response; } /** - * addPetWithHttpInfo + * Operation addPetWithHttpInfo * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +136,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -134,7 +148,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -147,7 +161,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -162,43 +176,46 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * deletePet + * Operation deletePet * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($pet_id, $api_key = null) { - list($response) = $this->deletePetWithHttpInfo ($pet_id, $api_key); - return $response; + list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); + return $response; } /** - * deletePetWithHttpInfo + * Operation deletePetWithHttpInfo * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -209,7 +226,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -221,7 +238,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // header params if ($api_key !== null) { @@ -240,7 +257,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -255,41 +272,44 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * findPetsByStatus + * Operation findPetsByStatus * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status) { - list($response) = $this->findPetsByStatusWithHttpInfo ($status); - return $response; + list($response) = $this->findPetsByStatusWithHttpInfo($status); + return $response; } /** - * findPetsByStatusWithHttpInfo + * Operation findPetsByStatusWithHttpInfo * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -300,7 +320,7 @@ class PetApi if ($status === null) { throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - + // parse inputs $resourcePath = "/pet/findByStatus"; $httpBody = ''; @@ -312,7 +332,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($status)) { $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); @@ -327,7 +347,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -342,48 +362,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * findPetsByTags + * Operation findPetsByTags * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTags($tags) { - list($response) = $this->findPetsByTagsWithHttpInfo ($tags); - return $response; + list($response) = $this->findPetsByTagsWithHttpInfo($tags); + return $response; } /** - * findPetsByTagsWithHttpInfo + * Operation findPetsByTagsWithHttpInfo * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -394,7 +419,7 @@ class PetApi if ($tags === null) { throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - + // parse inputs $resourcePath = "/pet/findByTags"; $httpBody = ''; @@ -406,7 +431,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($tags)) { $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); @@ -421,7 +446,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -436,48 +461,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * getPetById + * Operation getPetById * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) + * * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { - list($response) = $this->getPetByIdWithHttpInfo ($pet_id); - return $response; + list($response) = $this->getPetByIdWithHttpInfo($pet_id); + return $response; } /** - * getPetByIdWithHttpInfo + * Operation getPetByIdWithHttpInfo * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) + * * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -488,7 +518,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -500,7 +530,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -516,7 +546,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -533,48 +563,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * updatePet + * Operation updatePet * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePet($body) { - list($response) = $this->updatePetWithHttpInfo ($body); - return $response; + list($response) = $this->updatePetWithHttpInfo($body); + return $response; } /** - * updatePetWithHttpInfo + * Operation updatePetWithHttpInfo * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -585,7 +620,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -597,7 +632,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -610,7 +645,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -625,45 +660,48 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * updatePetWithForm + * Operation updatePetWithForm * - * Updates a pet in the store with form data + * 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) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name = null, $status = null) { - list($response) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); - return $response; + list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + return $response; } /** - * updatePetWithFormWithHttpInfo + * Operation updatePetWithFormWithHttpInfo * - * Updates a pet in the store with form data + * 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) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -674,7 +712,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -686,7 +724,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); - + // path params @@ -708,7 +746,7 @@ class PetApi $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -723,45 +761,48 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * uploadFile + * Operation uploadFile * - * uploads an image + * 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) + * * @return \Swagger\Client\Model\ApiResponse * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) { - list($response) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); - return $response; + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); + return $response; } /** - * uploadFileWithHttpInfo + * Operation uploadFileWithHttpInfo * - * uploads an image + * 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) + * * @return Array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -772,7 +813,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $httpBody = ''; @@ -784,7 +825,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); - + // path params @@ -808,11 +849,11 @@ class PetApi if (function_exists('curl_file_create')) { $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); } else { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -827,23 +868,26 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\ApiResponse' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\ApiResponse' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index a238eb41312..d19ddb6f8c5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -9,25 +9,32 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +59,41 @@ class StoreApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return StoreApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +101,31 @@ class StoreApi $this->apiClient = $apiClient; return $this; } - + /** - * deleteOrder + * Operation deleteOrder * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { - list($response) = $this->deleteOrderWithHttpInfo ($order_id); - return $response; + list($response) = $this->deleteOrderWithHttpInfo($order_id); + return $response; } /** - * deleteOrderWithHttpInfo + * Operation deleteOrderWithHttpInfo * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -126,7 +140,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -138,7 +152,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -154,7 +168,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -164,45 +178,48 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * getInventory + * Operation getInventory + * + * Returns pet inventories by status. * - * Returns pet inventories by status * * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { - list($response) = $this->getInventoryWithHttpInfo (); - return $response; + list($response) = $this->getInventoryWithHttpInfo(); + return $response; } /** - * getInventoryWithHttpInfo + * Operation getInventoryWithHttpInfo + * + * Returns pet inventories by status. * - * Returns pet inventories by status * * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventoryWithHttpInfo() { - + // parse inputs $resourcePath = "/store/inventory"; $httpBody = ''; @@ -214,7 +231,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -223,7 +240,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -240,48 +257,53 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'map[string,int]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'map[string,int]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * getOrderById + * Operation getOrderById * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { - list($response) = $this->getOrderByIdWithHttpInfo ($order_id); - return $response; + list($response) = $this->getOrderByIdWithHttpInfo($order_id); + return $response; } /** - * getOrderByIdWithHttpInfo + * Operation getOrderByIdWithHttpInfo * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -299,7 +321,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -311,7 +333,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -327,7 +349,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -337,48 +359,53 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * placeOrder + * Operation placeOrder * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrder($body) { - list($response) = $this->placeOrderWithHttpInfo ($body); - return $response; + list($response) = $this->placeOrderWithHttpInfo($body); + return $response; } /** - * placeOrderWithHttpInfo + * Operation placeOrderWithHttpInfo * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -389,7 +416,7 @@ class StoreApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - + // parse inputs $resourcePath = "/store/order"; $httpBody = ''; @@ -401,7 +428,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -414,7 +441,7 @@ class StoreApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -424,23 +451,26 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ed9744b8255..d735c083522 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -9,25 +9,32 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +59,41 @@ class UserApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return UserApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +101,31 @@ class UserApi $this->apiClient = $apiClient; return $this; } - + /** - * createUser + * Operation createUser * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUser($body) { - list($response) = $this->createUserWithHttpInfo ($body); - return $response; + list($response) = $this->createUserWithHttpInfo($body); + return $response; } /** - * createUserWithHttpInfo + * Operation createUserWithHttpInfo * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +136,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - + // parse inputs $resourcePath = "/user"; $httpBody = ''; @@ -134,7 +148,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -147,7 +161,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -157,41 +171,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithArrayInput + * Operation createUsersWithArrayInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInput($body) { - list($response) = $this->createUsersWithArrayInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithArrayInputWithHttpInfo($body); + return $response; } /** - * createUsersWithArrayInputWithHttpInfo + * Operation createUsersWithArrayInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,7 +219,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - + // parse inputs $resourcePath = "/user/createWithArray"; $httpBody = ''; @@ -214,7 +231,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -227,7 +244,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -237,41 +254,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithListInput + * Operation createUsersWithListInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInput($body) { - list($response) = $this->createUsersWithListInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithListInputWithHttpInfo($body); + return $response; } /** - * createUsersWithListInputWithHttpInfo + * Operation createUsersWithListInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -282,7 +302,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - + // parse inputs $resourcePath = "/user/createWithList"; $httpBody = ''; @@ -294,7 +314,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -307,7 +327,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -317,41 +337,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * deleteUser + * Operation deleteUser * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { - list($response) = $this->deleteUserWithHttpInfo ($username); - return $response; + list($response) = $this->deleteUserWithHttpInfo($username); + return $response; } /** - * deleteUserWithHttpInfo + * Operation deleteUserWithHttpInfo * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -362,7 +385,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -374,7 +397,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -390,7 +413,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -400,41 +423,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * getUserByName + * Operation getUserByName * - * Get user by user name + * 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) * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { - list($response) = $this->getUserByNameWithHttpInfo ($username); - return $response; + list($response) = $this->getUserByNameWithHttpInfo($username); + return $response; } /** - * getUserByNameWithHttpInfo + * Operation getUserByNameWithHttpInfo * - * Get user by user name + * 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) * @return Array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -445,7 +471,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -457,7 +483,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -473,7 +499,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -483,50 +509,55 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\User' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * loginUser + * Operation loginUser * - * Logs user into the system + * 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) + * * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUser($username, $password) { - list($response) = $this->loginUserWithHttpInfo ($username, $password); - return $response; + list($response) = $this->loginUserWithHttpInfo($username, $password); + return $response; } /** - * loginUserWithHttpInfo + * Operation loginUserWithHttpInfo * - * Logs user into the system + * 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) + * * @return Array of string, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -542,7 +573,7 @@ class UserApi if ($password === null) { throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - + // parse inputs $resourcePath = "/user/login"; $httpBody = ''; @@ -554,7 +585,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); @@ -569,7 +600,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -579,52 +610,57 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'string' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'string' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * logoutUser + * Operation logoutUser + * + * Logs out current logged in user session. * - * Logs out current logged in user session * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { - list($response) = $this->logoutUserWithHttpInfo (); - return $response; + list($response) = $this->logoutUserWithHttpInfo(); + return $response; } /** - * logoutUserWithHttpInfo + * Operation logoutUserWithHttpInfo + * + * Logs out current logged in user session. * - * Logs out current logged in user session * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUserWithHttpInfo() { - + // parse inputs $resourcePath = "/user/logout"; $httpBody = ''; @@ -636,7 +672,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -645,7 +681,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -655,43 +691,46 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, + $resourcePath, + 'GET', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * updateUser + * Operation updateUser * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { - list($response) = $this->updateUserWithHttpInfo ($username, $body); - return $response; + list($response) = $this->updateUserWithHttpInfo($username, $body); + return $response; } /** - * updateUserWithHttpInfo + * Operation updateUserWithHttpInfo * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -707,7 +746,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -719,7 +758,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -739,7 +778,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -749,16 +788,17 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index b28f2f26140..02fb8729620 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -55,18 +63,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\Swagger\Client\Configuration $config = null) @@ -81,6 +92,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +102,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +112,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +137,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ @@ -160,7 +177,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -171,7 +188,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -202,7 +219,7 @@ class ApiClient // debugging for curl if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); + error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); @@ -216,19 +233,19 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); // debug HTTP response body if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); + error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); } // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -246,7 +263,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -295,40 +314,35 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - - foreach(explode("\n", $raw_headers) as $h) - { + + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } else { + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } - + return $headers; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index d6040a0ff20..48551429c7f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -9,21 +9,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -48,30 +56,34 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -100,7 +112,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 9da9c7edac0..30b1b6c2dff 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -11,19 +11,25 @@ */ /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ /** @@ -47,7 +53,7 @@ namespace Swagger\Client; class Configuration { - private static $_defaultConfiguration = null; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -110,7 +116,7 @@ class Configuration * * @var string */ - protected $userAgent = "Swagger-Codegen/1.0.0/php"; + protected $userAgent = "Swagger-Codegen//php"; /** * Debug switch (default set to false) @@ -487,11 +493,11 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$_defaultConfiguration == null) { - self::$_defaultConfiguration = new Configuration(); + if (self::$defaultConfiguration == null) { + self::$defaultConfiguration = new Configuration(); } - return self::$_defaultConfiguration; + return self::$defaultConfiguration; } /** @@ -503,7 +509,7 @@ class Configuration */ public static function setDefaultConfiguration(Configuration $config) { - self::$_defaultConfiguration = $config; + self::$defaultConfiguration = $config; } /** @@ -513,14 +519,13 @@ class Configuration */ public static function toDebugReport() { - $report = "PHP SDK (Swagger\Client) Debug Report:\n"; - $report .= " OS: ".php_uname()."\n"; - $report .= " PHP Version: ".phpversion()."\n"; - $report .= " OpenAPI Spec Version: 1.0.0\n"; - $report .= " SDK Package Version: 1.0.0\n"; - $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; + $report = "PHP SDK (Swagger\Client) Debug Report:".PHP_EOL; + $report .= " OS: ".php_uname().PHP_EOL; + $report .= " PHP Version: ".phpversion().PHP_EOL; + $report .= " OpenAPI Spec Version: 1.0.0".PHP_EOL; + $report .= " SDK Package Version: ".PHP_EOL; + $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath().PHP_EOL; return $report; } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php new file mode 100644 index 00000000000..4b5703134c1 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -0,0 +1,212 @@ +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(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 9120535bf5a..33ee60a0b7a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Animal Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +58,33 @@ class Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Animal'; + protected static $swaggerModelName = 'Animal'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'class_name' => 'string', 'color' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'class_name' => 'className', 'color' => 'color' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +92,13 @@ class Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'class_name' => 'setClassName', 'color' => 'setColor' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +106,13 @@ class Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'class_name' => 'getClassName', 'color' => 'getColor' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,14 +142,14 @@ class Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['class_name'] === null) { - $invalid_properties[] = "'$class_name' can't be null"; + $invalid_properties[] = "'class_name' can't be null"; } return $invalid_properties; } @@ -146,8 +157,8 @@ class Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -169,7 +180,7 @@ class Animal implements ArrayAccess /** * Sets class_name - * @param string $class_name + * @param string $class_name * @return $this */ public function setClassName($class_name) @@ -190,7 +201,7 @@ class Animal implements ArrayAccess /** * Sets color - * @param string $color + * @param string $color * @return $this */ public function setColor($color) @@ -201,7 +212,7 @@ class Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -211,17 +222,17 @@ class Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -233,17 +244,17 @@ class Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 2ff9da6a4ea..e9857f27f76 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * AnimalFarm Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +58,31 @@ class AnimalFarm implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'AnimalFarm'; + protected static $swaggerModelName = 'AnimalFarm'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +90,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +103,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -121,10 +132,10 @@ class AnimalFarm implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -133,8 +144,8 @@ class AnimalFarm implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +154,7 @@ class AnimalFarm implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +164,17 @@ class AnimalFarm implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +186,17 @@ class AnimalFarm implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 8894f835aea..fc9c4c2abed 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * ApiResponse Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,33 +58,35 @@ class ApiResponse implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'ApiResponse'; + protected static $swaggerModelName = 'ApiResponse'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'code' => 'int', 'type' => 'string', 'message' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'code' => 'code', 'type' => 'type', 'message' => 'message' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +94,14 @@ class ApiResponse implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'code' => 'setCode', 'type' => 'setType', 'message' => 'setMessage' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +109,14 @@ class ApiResponse implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'code' => 'getCode', 'type' => 'getType', 'message' => 'getMessage' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -132,10 +143,10 @@ class ApiResponse implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -144,8 +155,8 @@ class ApiResponse implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -164,7 +175,7 @@ class ApiResponse implements ArrayAccess /** * Sets code - * @param int $code + * @param int $code * @return $this */ public function setCode($code) @@ -185,7 +196,7 @@ class ApiResponse implements ArrayAccess /** * Sets type - * @param string $type + * @param string $type * @return $this */ public function setType($type) @@ -206,7 +217,7 @@ class ApiResponse implements ArrayAccess /** * Sets message - * @param string $message + * @param string $message * @return $this */ public function setMessage($message) @@ -217,7 +228,7 @@ class ApiResponse implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -227,17 +238,17 @@ class ApiResponse implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -249,17 +260,17 @@ class ApiResponse implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php new file mode 100644 index 00000000000..44af1286a6d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -0,0 +1,212 @@ +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(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 393f89e5b0f..efabd53cbbc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Cat Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +58,31 @@ class Cat extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Cat'; + protected static $swaggerModelName = 'Cat'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'declawed' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'declawed' => 'declawed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +90,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'declawed' => 'setDeclawed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +103,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'declawed' => 'getDeclawed' ); - - static function getters() { + + public static function getters() + { return parent::getters() + self::$getters; } @@ -124,10 +135,10 @@ class Cat extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -136,8 +147,8 @@ class Cat extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -156,7 +167,7 @@ class Cat extends Animal implements ArrayAccess /** * Sets declawed - * @param bool $declawed + * @param bool $declawed * @return $this */ public function setDeclawed($declawed) @@ -167,7 +178,7 @@ class Cat extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +188,17 @@ class Cat extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +210,17 @@ class Cat extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 1c1a2340378..d9ff6aa58e2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Category Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +58,33 @@ class Category implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Category'; + protected static $swaggerModelName = 'Category'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +92,13 @@ class Category implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +106,13 @@ class Category implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -127,10 +138,10 @@ class Category implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -139,8 +150,8 @@ class Category implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -159,7 +170,7 @@ class Category implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -180,7 +191,7 @@ class Category implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -191,7 +202,7 @@ class Category implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +212,17 @@ class Category implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +234,17 @@ class Category implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index b79e76a4187..081fbd4837d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Dog Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +58,31 @@ class Dog extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Dog'; + protected static $swaggerModelName = 'Dog'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'breed' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'breed' => 'breed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +90,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'breed' => 'setBreed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +103,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'breed' => 'getBreed' ); - - static function getters() { + + public static function getters() + { return parent::getters() + self::$getters; } @@ -124,10 +135,10 @@ class Dog extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -136,8 +147,8 @@ class Dog extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -156,7 +167,7 @@ class Dog extends Animal implements ArrayAccess /** * Sets breed - * @param string $breed + * @param string $breed * @return $this */ public function setBreed($breed) @@ -167,7 +178,7 @@ class Dog extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +188,17 @@ class Dog extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +210,17 @@ class Dog extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 2b6d36c9b66..4c67a277dde 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * EnumClass Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +58,31 @@ class EnumClass implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'EnumClass'; + protected static $swaggerModelName = 'EnumClass'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +90,12 @@ class EnumClass implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +103,12 @@ class EnumClass implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -121,10 +132,10 @@ class EnumClass implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -133,8 +144,8 @@ class EnumClass implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +154,7 @@ class EnumClass implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +164,17 @@ class EnumClass implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +186,17 @@ class EnumClass implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string 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 6e10f45dd8f..673b3ce3624 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * EnumTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,33 +58,35 @@ class EnumTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Enum_Test'; + protected static $swaggerModelName = 'Enum_Test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'enum_string' => 'string', 'enum_integer' => 'int', 'enum_number' => 'double' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', 'enum_number' => 'enum_number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +94,14 @@ class EnumTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'enum_string' => 'setEnumString', 'enum_integer' => 'setEnumInteger', 'enum_number' => 'setEnumNumber' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +109,14 @@ class EnumTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'enum_string' => 'getEnumString', 'enum_integer' => 'getEnumInteger', 'enum_number' => 'getEnumNumber' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,7 +133,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumStringAllowableValues() { + public function getEnumStringAllowableValues() + { return [ self::ENUM_STRING_UPPER, self::ENUM_STRING_LOWER, @@ -133,7 +145,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumIntegerAllowableValues() { + public function getEnumIntegerAllowableValues() + { return [ self::ENUM_INTEGER_1, self::ENUM_INTEGER_MINUS_1, @@ -144,7 +157,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumNumberAllowableValues() { + public function getEnumNumberAllowableValues() + { return [ self::ENUM_NUMBER_1_DOT_1, self::ENUM_NUMBER_MINUS_1_DOT_2, @@ -171,23 +185,23 @@ class EnumTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); $allowed_values = array("UPPER", "lower"); if (!in_array($this->container['enum_string'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_string', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; } $allowed_values = array("1", "-1"); if (!in_array($this->container['enum_integer'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_integer', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_integer', must be one of #{allowed_values}."; } $allowed_values = array("1.1", "-1.2"); if (!in_array($this->container['enum_number'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_number', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_number', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -195,8 +209,8 @@ class EnumTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -227,7 +241,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_string - * @param string $enum_string + * @param string $enum_string * @return $this */ public function setEnumString($enum_string) @@ -252,7 +266,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_integer - * @param int $enum_integer + * @param int $enum_integer * @return $this */ public function setEnumInteger($enum_integer) @@ -277,7 +291,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_number - * @param double $enum_number + * @param double $enum_number * @return $this */ public function setEnumNumber($enum_number) @@ -292,7 +306,7 @@ class EnumTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -302,17 +316,17 @@ class EnumTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -324,17 +338,17 @@ class EnumTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string 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 bf674b05102..e9b8bc9cf7f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * FormatTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +58,13 @@ class FormatTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'format_test'; + protected static $swaggerModelName = 'format_test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'integer' => 'int', 'int32' => 'int', 'int64' => 'int', @@ -73,15 +80,16 @@ class FormatTest implements ArrayAccess 'password' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'integer' => 'integer', 'int32' => 'int32', 'int64' => 'int64', @@ -97,7 +105,8 @@ class FormatTest implements ArrayAccess 'password' => 'password' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -105,7 +114,7 @@ class FormatTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'integer' => 'setInteger', 'int32' => 'setInt32', 'int64' => 'setInt64', @@ -121,7 +130,8 @@ class FormatTest implements ArrayAccess 'password' => 'setPassword' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -129,7 +139,7 @@ class FormatTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'integer' => 'getInteger', 'int32' => 'getInt32', 'int64' => 'getInt64', @@ -144,8 +154,9 @@ class FormatTest implements ArrayAccess 'uuid' => 'getUuid', 'password' => 'getPassword' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -182,62 +193,62 @@ class FormatTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['integer'] > 100.0) { - $invalid_properties[] = "invalid value for '$integer', must be smaller than or equal to 100.0."; + $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100.0."; } if ($this->container['integer'] < 10.0) { - $invalid_properties[] = "invalid value for '$integer', must be bigger than or equal to 10.0."; + $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10.0."; } if ($this->container['int32'] > 200.0) { - $invalid_properties[] = "invalid value for '$int32', must be smaller than or equal to 200.0."; + $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200.0."; } if ($this->container['int32'] < 20.0) { - $invalid_properties[] = "invalid value for '$int32', must be bigger than or equal to 20.0."; + $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20.0."; } if ($this->container['number'] === null) { - $invalid_properties[] = "'$number' can't be null"; + $invalid_properties[] = "'number' can't be null"; } if ($this->container['number'] > 543.2) { - $invalid_properties[] = "invalid value for '$number', must be smaller than or equal to 543.2."; + $invalid_properties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; } if ($this->container['number'] < 32.1) { - $invalid_properties[] = "invalid value for '$number', must be bigger than or equal to 32.1."; + $invalid_properties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; } if ($this->container['float'] > 987.6) { - $invalid_properties[] = "invalid value for '$float', must be smaller than or equal to 987.6."; + $invalid_properties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; } if ($this->container['float'] < 54.3) { - $invalid_properties[] = "invalid value for '$float', must be bigger than or equal to 54.3."; + $invalid_properties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; } if ($this->container['double'] > 123.4) { - $invalid_properties[] = "invalid value for '$double', must be smaller than or equal to 123.4."; + $invalid_properties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; } if ($this->container['double'] < 67.8) { - $invalid_properties[] = "invalid value for '$double', must be bigger than or equal to 67.8."; + $invalid_properties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; } if (!preg_match("/[a-z]/i", $this->container['string'])) { - $invalid_properties[] = "invalid value for '$string', must be conform to the pattern /[a-z]/i."; + $invalid_properties[] = "invalid value for 'string', must be conform to the pattern /[a-z]/i."; } if ($this->container['byte'] === null) { - $invalid_properties[] = "'$byte' can't be null"; + $invalid_properties[] = "'byte' can't be null"; } if ($this->container['date'] === null) { - $invalid_properties[] = "'$date' can't be null"; + $invalid_properties[] = "'date' can't be null"; } if ($this->container['password'] === null) { - $invalid_properties[] = "'$password' can't be null"; + $invalid_properties[] = "'password' can't be null"; } if (strlen($this->container['password']) > 64) { - $invalid_properties[] = "invalid value for '$password', the character length must be smaller than or equal to 64."; + $invalid_properties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; } if (strlen($this->container['password']) < 10) { - $invalid_properties[] = "invalid value for '$password', the character length must be bigger than or equal to 10."; + $invalid_properties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; } return $invalid_properties; } @@ -245,8 +256,8 @@ class FormatTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -316,7 +327,7 @@ class FormatTest implements ArrayAccess /** * Sets integer - * @param int $integer + * @param int $integer * @return $this */ public function setInteger($integer) @@ -344,7 +355,7 @@ class FormatTest implements ArrayAccess /** * Sets int32 - * @param int $int32 + * @param int $int32 * @return $this */ public function setInt32($int32) @@ -372,7 +383,7 @@ class FormatTest implements ArrayAccess /** * Sets int64 - * @param int $int64 + * @param int $int64 * @return $this */ public function setInt64($int64) @@ -393,7 +404,7 @@ class FormatTest implements ArrayAccess /** * Sets number - * @param float $number + * @param float $number * @return $this */ public function setNumber($number) @@ -421,7 +432,7 @@ class FormatTest implements ArrayAccess /** * Sets float - * @param float $float + * @param float $float * @return $this */ public function setFloat($float) @@ -449,7 +460,7 @@ class FormatTest implements ArrayAccess /** * Sets double - * @param double $double + * @param double $double * @return $this */ public function setDouble($double) @@ -477,7 +488,7 @@ class FormatTest implements ArrayAccess /** * Sets string - * @param string $string + * @param string $string * @return $this */ public function setString($string) @@ -502,7 +513,7 @@ class FormatTest implements ArrayAccess /** * Sets byte - * @param string $byte + * @param string $byte * @return $this */ public function setByte($byte) @@ -523,7 +534,7 @@ class FormatTest implements ArrayAccess /** * Sets binary - * @param string $binary + * @param string $binary * @return $this */ public function setBinary($binary) @@ -544,7 +555,7 @@ class FormatTest implements ArrayAccess /** * Sets date - * @param \DateTime $date + * @param \DateTime $date * @return $this */ public function setDate($date) @@ -565,7 +576,7 @@ class FormatTest implements ArrayAccess /** * Sets date_time - * @param \DateTime $date_time + * @param \DateTime $date_time * @return $this */ public function setDateTime($date_time) @@ -586,7 +597,7 @@ class FormatTest implements ArrayAccess /** * Sets uuid - * @param string $uuid + * @param string $uuid * @return $this */ public function setUuid($uuid) @@ -607,7 +618,7 @@ class FormatTest implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) @@ -624,7 +635,7 @@ class FormatTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -634,17 +645,17 @@ class FormatTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -656,17 +667,17 @@ class FormatTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php new file mode 100644 index 00000000000..fd397440cfc --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -0,0 +1,260 @@ + 'string', + 'date_time' => '\DateTime' + ); + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = array( + 'uuid' => 'uuid', + 'date_time' => 'dateTime' + ); + + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = array( + 'uuid' => 'setUuid', + 'date_time' => 'setDateTime' + ); + + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = array( + 'uuid' => 'getUuid', + 'date_time' => 'getDateTime' + ); + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array(); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing 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; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets uuid + * @return string + */ + public function getUuid() + { + return $this->container['uuid']; + } + + /** + * Sets uuid + * @param string $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 + * @return $this + */ + public function setDateTime($date_time) + { + $this->container['date_time'] = $date_time; + + 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(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 68eae680dc6..f6d9a4e2e10 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -51,29 +59,31 @@ class Model200Response implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '200_response'; + protected static $swaggerModelName = '200_response'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +91,12 @@ class Model200Response implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +104,12 @@ class Model200Response implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +134,10 @@ class Model200Response implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +146,8 @@ class Model200Response implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +166,7 @@ class Model200Response implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) @@ -165,7 +177,7 @@ class Model200Response implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +187,17 @@ class Model200Response implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +209,17 @@ class Model200Response implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 7dce6f0029d..f39fbd0bdef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -51,29 +59,31 @@ class ModelReturn implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Return'; + protected static $swaggerModelName = 'Return'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'return' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'return' => 'return' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +91,12 @@ class ModelReturn implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'return' => 'setReturn' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +104,12 @@ class ModelReturn implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'return' => 'getReturn' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +134,10 @@ class ModelReturn implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +146,8 @@ class ModelReturn implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +166,7 @@ class ModelReturn implements ArrayAccess /** * Sets return - * @param int $return + * @param int $return * @return $this */ public function setReturn($return) @@ -165,7 +177,7 @@ class ModelReturn implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +187,17 @@ class ModelReturn implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +209,17 @@ class ModelReturn implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index b77f3d78d0c..32dac8410f2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -51,35 +59,37 @@ class Name implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Name'; + protected static $swaggerModelName = 'Name'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int', 'snake_case' => 'int', 'property' => 'string', '_123_number' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name', 'snake_case' => 'snake_case', 'property' => 'property', '_123_number' => '123Number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -87,14 +97,15 @@ class Name implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName', 'snake_case' => 'setSnakeCase', 'property' => 'setProperty', '_123_number' => 'set123Number' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -102,14 +113,15 @@ class Name implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName', 'snake_case' => 'getSnakeCase', 'property' => 'getProperty', '_123_number' => 'get123Number' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -137,14 +149,14 @@ class Name implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } return $invalid_properties; } @@ -152,8 +164,8 @@ class Name implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -175,7 +187,7 @@ class Name implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) @@ -196,7 +208,7 @@ class Name implements ArrayAccess /** * Sets snake_case - * @param int $snake_case + * @param int $snake_case * @return $this */ public function setSnakeCase($snake_case) @@ -217,7 +229,7 @@ class Name implements ArrayAccess /** * Sets property - * @param string $property + * @param string $property * @return $this */ public function setProperty($property) @@ -238,7 +250,7 @@ class Name implements ArrayAccess /** * Sets _123_number - * @param int $_123_number + * @param int $_123_number * @return $this */ public function set123Number($_123_number) @@ -249,7 +261,7 @@ class Name implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -259,17 +271,17 @@ class Name implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -281,17 +293,17 @@ class Name implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string 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 88779ed8c73..cf5f61a9640 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Order Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +58,13 @@ class Order implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Order'; + protected static $swaggerModelName = 'Order'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'pet_id' => 'int', 'quantity' => 'int', @@ -66,15 +73,16 @@ class Order implements ArrayAccess 'complete' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'pet_id' => 'petId', 'quantity' => 'quantity', @@ -83,7 +91,8 @@ class Order implements ArrayAccess 'complete' => 'complete' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +100,7 @@ class Order implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'pet_id' => 'setPetId', 'quantity' => 'setQuantity', @@ -100,7 +109,8 @@ class Order implements ArrayAccess 'complete' => 'setComplete' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +118,7 @@ class Order implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'pet_id' => 'getPetId', 'quantity' => 'getQuantity', @@ -116,8 +126,9 @@ class Order implements ArrayAccess 'status' => 'getStatus', 'complete' => 'getComplete' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,7 +142,8 @@ class Order implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ self::STATUS_PLACED, self::STATUS_APPROVED, @@ -162,15 +174,15 @@ class Order implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); $allowed_values = array("placed", "approved", "delivered"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -178,8 +190,8 @@ class Order implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -202,7 +214,7 @@ class Order implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -223,7 +235,7 @@ class Order implements ArrayAccess /** * Sets pet_id - * @param int $pet_id + * @param int $pet_id * @return $this */ public function setPetId($pet_id) @@ -244,7 +256,7 @@ class Order implements ArrayAccess /** * Sets quantity - * @param int $quantity + * @param int $quantity * @return $this */ public function setQuantity($quantity) @@ -265,7 +277,7 @@ class Order implements ArrayAccess /** * Sets ship_date - * @param \DateTime $ship_date + * @param \DateTime $ship_date * @return $this */ public function setShipDate($ship_date) @@ -311,7 +323,7 @@ class Order implements ArrayAccess /** * Sets complete - * @param bool $complete + * @param bool $complete * @return $this */ public function setComplete($complete) @@ -322,7 +334,7 @@ class Order implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -332,17 +344,17 @@ class Order implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -354,17 +366,17 @@ class Order implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string 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 5a65e432538..a81e9eb33f9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Pet Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +58,13 @@ class Pet implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Pet'; + protected static $swaggerModelName = 'Pet'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'category' => '\Swagger\Client\Model\Category', 'name' => 'string', @@ -66,15 +73,16 @@ class Pet implements ArrayAccess 'status' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'category' => 'category', 'name' => 'name', @@ -83,7 +91,8 @@ class Pet implements ArrayAccess 'status' => 'status' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +100,7 @@ class Pet implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'category' => 'setCategory', 'name' => 'setName', @@ -100,7 +109,8 @@ class Pet implements ArrayAccess 'status' => 'setStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +118,7 @@ class Pet implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'category' => 'getCategory', 'name' => 'getName', @@ -116,8 +126,9 @@ class Pet implements ArrayAccess 'tags' => 'getTags', 'status' => 'getStatus' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,7 +142,8 @@ class Pet implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ self::STATUS_AVAILABLE, self::STATUS_PENDING, @@ -162,21 +174,21 @@ class Pet implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } if ($this->container['photo_urls'] === null) { - $invalid_properties[] = "'$photo_urls' can't be null"; + $invalid_properties[] = "'photo_urls' can't be null"; } $allowed_values = array("available", "pending", "sold"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -184,8 +196,8 @@ class Pet implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -214,7 +226,7 @@ class Pet implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -235,7 +247,7 @@ class Pet implements ArrayAccess /** * Sets category - * @param \Swagger\Client\Model\Category $category + * @param \Swagger\Client\Model\Category $category * @return $this */ public function setCategory($category) @@ -256,7 +268,7 @@ class Pet implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -277,7 +289,7 @@ class Pet implements ArrayAccess /** * Sets photo_urls - * @param string[] $photo_urls + * @param string[] $photo_urls * @return $this */ public function setPhotoUrls($photo_urls) @@ -298,7 +310,7 @@ class Pet implements ArrayAccess /** * Sets tags - * @param \Swagger\Client\Model\Tag[] $tags + * @param \Swagger\Client\Model\Tag[] $tags * @return $this */ public function setTags($tags) @@ -334,7 +346,7 @@ class Pet implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -344,17 +356,17 @@ class Pet implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -366,17 +378,17 @@ class Pet implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php new file mode 100644 index 00000000000..22e534a51e5 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -0,0 +1,260 @@ + 'string', + 'baz' => 'string' + ); + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = array( + 'bar' => 'bar', + 'baz' => 'baz' + ); + + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = array( + 'bar' => 'setBar', + 'baz' => 'setBaz' + ); + + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = array( + 'bar' => 'getBar', + 'baz' => 'getBaz' + ); + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array(); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing 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() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets bar + * @return string + */ + public function getBar() + { + return $this->container['bar']; + } + + /** + * Sets bar + * @param string $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 + * @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(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 25ebecd55a0..e7c97a5ef56 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * SpecialModelName Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +58,31 @@ class SpecialModelName implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '$special[model.name]'; + protected static $swaggerModelName = '$special[model.name]'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'special_property_name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'special_property_name' => '$special[property.name]' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +90,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'special_property_name' => 'setSpecialPropertyName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +103,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'special_property_name' => 'getSpecialPropertyName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +133,10 @@ class SpecialModelName implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +145,8 @@ class SpecialModelName implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +165,7 @@ class SpecialModelName implements ArrayAccess /** * Sets special_property_name - * @param int $special_property_name + * @param int $special_property_name * @return $this */ public function setSpecialPropertyName($special_property_name) @@ -165,7 +176,7 @@ class SpecialModelName implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +186,17 @@ class SpecialModelName implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +208,17 @@ class SpecialModelName implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index a2132ca7e5c..6a378c7f349 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * Tag Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +58,33 @@ class Tag implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Tag'; + protected static $swaggerModelName = 'Tag'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +92,13 @@ class Tag implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +106,13 @@ class Tag implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -127,10 +138,10 @@ class Tag implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -139,8 +150,8 @@ class Tag implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -159,7 +170,7 @@ class Tag implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -180,7 +191,7 @@ class Tag implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -191,7 +202,7 @@ class Tag implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +212,17 @@ class Tag implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +234,17 @@ class Tag implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index a97727f0a8f..e61af43c647 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -10,21 +10,29 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ + /** - * Copyright 2016 SmartBear Software + * Swagger Petstore * - * 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 + * 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. + * 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. */ + /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -39,7 +47,6 @@ use \ArrayAccess; * User Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +58,13 @@ class User implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'User'; + protected static $swaggerModelName = 'User'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'username' => 'string', 'first_name' => 'string', @@ -68,15 +75,16 @@ class User implements ArrayAccess 'user_status' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'username' => 'username', 'first_name' => 'firstName', @@ -87,7 +95,8 @@ class User implements ArrayAccess 'user_status' => 'userStatus' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -95,7 +104,7 @@ class User implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'username' => 'setUsername', 'first_name' => 'setFirstName', @@ -106,7 +115,8 @@ class User implements ArrayAccess 'user_status' => 'setUserStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -114,7 +124,7 @@ class User implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'username' => 'getUsername', 'first_name' => 'getFirstName', @@ -124,8 +134,9 @@ class User implements ArrayAccess 'phone' => 'getPhone', 'user_status' => 'getUserStatus' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -157,10 +168,10 @@ class User implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -169,8 +180,8 @@ class User implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -189,7 +200,7 @@ class User implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -210,7 +221,7 @@ class User implements ArrayAccess /** * Sets username - * @param string $username + * @param string $username * @return $this */ public function setUsername($username) @@ -231,7 +242,7 @@ class User implements ArrayAccess /** * Sets first_name - * @param string $first_name + * @param string $first_name * @return $this */ public function setFirstName($first_name) @@ -252,7 +263,7 @@ class User implements ArrayAccess /** * Sets last_name - * @param string $last_name + * @param string $last_name * @return $this */ public function setLastName($last_name) @@ -273,7 +284,7 @@ class User implements ArrayAccess /** * Sets email - * @param string $email + * @param string $email * @return $this */ public function setEmail($email) @@ -294,7 +305,7 @@ class User implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) @@ -315,7 +326,7 @@ class User implements ArrayAccess /** * Sets phone - * @param string $phone + * @param string $phone * @return $this */ public function setPhone($phone) @@ -347,7 +358,7 @@ class User implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -357,17 +368,17 @@ class User implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @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 integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -379,17 +390,17 @@ class User implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 3adaa899f5f..ce77aa6c3b3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -1,6 +1,6 @@ getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - return $deserialized; + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + + return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +294,11 @@ class ObjectSerializer $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, $discriminator)); diff --git a/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml new file mode 100644 index 00000000000..a0173077aa9 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml @@ -0,0 +1,10 @@ + + + + Arnes Drupal code checker + + + + * + + diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php index dc599fbe5d7..7736ffd67a7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,24 +53,27 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for testEndpointParameters * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * */ - public function test_testEndpointParameters() { + public function testTestEndpointParameters() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php index af6b1018332..73a7b06b5eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,87 +53,97 @@ class PetApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for addPet * - * Add a new pet to the store + * Add a new pet to the store. * */ - public function test_addPet() { + public function testAddPet() + { } /** * Test case for deletePet * - * Deletes a pet + * Deletes a pet. * */ - public function test_deletePet() { + public function testDeletePet() + { } /** * Test case for findPetsByStatus * - * Finds Pets by status + * Finds Pets by status. * */ - public function test_findPetsByStatus() { + public function testFindPetsByStatus() + { } /** * Test case for findPetsByTags * - * Finds Pets by tags + * Finds Pets by tags. * */ - public function test_findPetsByTags() { + public function testFindPetsByTags() + { } /** * Test case for getPetById * - * Find pet by ID + * Find pet by ID. * */ - public function test_getPetById() { + public function testGetPetById() + { } /** * Test case for updatePet * - * Update an existing pet + * Update an existing pet. * */ - public function test_updatePet() { + public function testUpdatePet() + { } /** * Test case for updatePetWithForm * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * */ - public function test_updatePetWithForm() { + public function testUpdatePetWithForm() + { } /** * Test case for uploadFile * - * uploads an image + * uploads an image. * */ - public function test_uploadFile() { + public function testUploadFile() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php index 25fa53169f2..aaa2df27fd7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,51 +53,57 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for deleteOrder * - * Delete purchase order by ID + * Delete purchase order by ID. * */ - public function test_deleteOrder() { + public function testDeleteOrder() + { } /** * Test case for getInventory * - * Returns pet inventories by status + * Returns pet inventories by status. * */ - public function test_getInventory() { + public function testGetInventory() + { } /** * Test case for getOrderById * - * Find purchase order by ID + * Find purchase order by ID. * */ - public function test_getOrderById() { + public function testGetOrderById() + { } /** * Test case for placeOrder * - * Place an order for a pet + * Place an order for a pet. * */ - public function test_placeOrder() { + public function testPlaceOrder() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php index 5df577e6d9e..c866015cf7a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,87 +53,97 @@ class UserApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for createUser * - * Create user + * Create user. * */ - public function test_createUser() { + public function testCreateUser() + { } /** * Test case for createUsersWithArrayInput * - * Creates list of users with given input array + * Creates list of users with given input array. * */ - public function test_createUsersWithArrayInput() { + public function testCreateUsersWithArrayInput() + { } /** * Test case for createUsersWithListInput * - * Creates list of users with given input array + * Creates list of users with given input array. * */ - public function test_createUsersWithListInput() { + public function testCreateUsersWithListInput() + { } /** * Test case for deleteUser * - * Delete user + * Delete user. * */ - public function test_deleteUser() { + public function testDeleteUser() + { } /** * Test case for getUserByName * - * Get user by user name + * Get user by user name. * */ - public function test_getUserByName() { + public function testGetUserByName() + { } /** * Test case for loginUser * - * Logs user into the system + * Logs user into the system. * */ - public function test_loginUser() { + public function testLoginUser() + { } /** * Test case for logoutUser * - * Logs out current logged in user session + * Logs out current logged in user session. * */ - public function test_logoutUser() { + public function testLogoutUser() + { } /** * Test case for updateUser * - * Updated user + * Updated user. * */ - public function test_updateUser() { + public function testUpdateUser() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php new file mode 100644 index 00000000000..d5150f44b8d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php @@ -0,0 +1,72 @@ +assertSame(Swagger\Client\Model\EnumClass::ABC, "_abc"); + $this->assertSame(Swagger\Client\Model\EnumClass::EFG, "-efg"); + $this->assertSame(Swagger\Client\Model\EnumClass::XYZ, "(xyz)"); } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php index 653a5129739..2cf9956b8b4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * EnumTestTest Class Doc Comment * * @category Class - * @description + * @description EnumTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,29 @@ class EnumTestTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test EnumTest + * Test "EnumTest" */ - public function testEnumTest() { - + public function testEnumTest() + { + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_STRING_UPPER, "UPPER"); + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_STRING_LOWER, "lower"); + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_INTEGER_1, 1); + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_INTEGER_MINUS_1, -1); + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_NUMBER_1_DOT_1, 1.1); + $this->assertSame(Swagger\Client\Model\EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2); } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php index ca9f9a71849..57675f2eada 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * FormatTestTest Class Doc Comment * * @category Class - * @description + * @description FormatTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class FormatTestTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test FormatTest + * Test "FormatTest" */ - public function testFormatTest() { + public function testFormatTest() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php new file mode 100644 index 00000000000..cd70c290959 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php @@ -0,0 +1,72 @@ +assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); @@ -22,8 +22,4 @@ class ObjectSerializerTest extends \PHPUnit_Framework_TestCase $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 8ef5a8e5058..8b5c8f7e499 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -1,12 +1,13 @@ assertSame(Swagger\Client\Model\Order::STATUS_PLACED, "placed"); - $this->assertSame(Swagger\Client\Model\Order::STATUS_APPROVED, "approved"); + $this->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 Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("placed"); $this->assertSame("placed", $order->getStatus()); @@ -31,11 +32,11 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase /** * @expectedException InvalidArgumentException - */ + */ public function testOrderException() { // initialize the API client - $order = new Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("invalid_value"); } @@ -52,13 +53,16 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase "complete": false } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order' + ); $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->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); $this->assertSame("placed", $order->getStatus()); $this->assertSame(false, $order->getComplete()); } @@ -76,16 +80,19 @@ ORDER; "complete": false }]] ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order[][]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order[][]' + ); - $this->assertArrayHasKey(0, $order); + $this->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->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); $this->assertSame("placed", $_order->getStatus()); $this->assertSame(false, $_order->getComplete()); } @@ -107,21 +114,20 @@ ORDER; } } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'map[string,map[string,\Swagger\Client\Model\Order]]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'map[string,map[string,\Swagger\Client\Model\Order]]' + ); - $this->assertArrayHasKey('test', $order); + $this->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->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/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 9feabf142cf..fa3733a8be2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,16 +1,17 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setPhotoUrls(array("http://test_php_unit_test.com")); // new tag - $tag= new Swagger\Client\Model\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 Swagger\Client\Model\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 Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } // test static functions defined in ApiClient public function testApiClient() - { + { // test selectHeaderAccept - $api_client = new Swagger\Client\ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); + $api_client = new ApiClient(); + $this->assertSame('application/json', $api_client->selectHeaderAccept(array( + 'application/xml', + 'application/json' + ))); + $this->assertSame(null, $api_client->selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array( + 'application/yaml', + 'application/xml' + ))); // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', $api_client->selectHeaderContentType(array( + 'application/xml', + 'application/json' + ))); $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array( + 'application/yaml', + 'application/xml' + ))); // test addDefaultHeader and getDefaultHeader $api_client->getConfig()->addDefaultHeader('test1', 'value1'); @@ -74,16 +87,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api2 = new Swagger\Client\Api\PetApi(); - $config3 = new Swagger\Client\Configuration(); - $apiClient3 = new Swagger\Client\ApiClient($config3); + $pet_api2 = new Api\PetApi(); + $config3 = new Configuration(); + $apiClient3 = new ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Swagger\Client\Configuration(); - $apiClient4 = new Swagger\Client\ApiClient($config4); + $config4 = new Configuration(); + $apiClient4 = new ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetApi($apiClient3); + $pet_api3 = new Api\PetApi($apiClient3); - // 2 different api clients are not the same + // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); @@ -98,7 +111,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); @@ -111,7 +124,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->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 * @@ -120,7 +133,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (inline model) $response = $pet_api->getPetByIdInObject($pet_id); @@ -144,7 +157,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); @@ -162,18 +175,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetByStatus() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['status'], "available"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -182,18 +195,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetsByTags() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByTags("test php tag"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['tags'][0]['name'], "test php tag"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -202,19 +215,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // create updated pet object - $updated_pet = new Swagger\Client\Model\Pet; + $updated_pet = new Model\Pet; $updated_pet->setId($pet_id); $updated_pet->setName('updatePet'); // new name $updated_pet->setStatus('pending'); // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); // verify updated Pet $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); @@ -226,12 +239,15 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithFormWithHttpInfo() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); + list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( + $pet_id, + 'update pet with form with http info' + ); // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); @@ -245,14 +261,14 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithForm() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form'); @@ -263,17 +279,17 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) - $this->assertSame($add_response, NULL); + $this->assertSame($add_response, null); // verify added Pet $response = $pet_api->getPetById($new_pet_id); $this->assertSame($response->getId(), $new_pet_id); @@ -288,28 +304,28 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPetUsingByteArray() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 3"); // new tag - $tag= new Swagger\Client\Model\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 Swagger\Client\Model\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 Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) - $object_serializer = new Swagger\Client\ObjectSerializer(); + $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) @@ -325,13 +341,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUploadFile() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // upload file $pet_id = 10001; $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); - // return ApiResponse + // return ApiResponse $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); } @@ -340,10 +356,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $api_client = new APIClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -359,10 +375,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetPetByIdWithByteArray() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $api_client = new APIClient($config); + $pet_api = new Api\PetApi($api_client); // test getPetByIdWithByteArray $pet_id = 10005; $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); @@ -383,7 +399,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test empty object serialization public function testEmptyPetSerialization() { - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; // the empty object should be serialised to {} $this->assertSame("{}", "$new_pet"); @@ -392,7 +408,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test inheritance in the model public function testInheritance() { - $new_dog = new Swagger\Client\Model\Dog; + $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 @@ -408,7 +424,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 'class_name' => 'Dog', 'breed' => 'Great Dane' ); - $new_dog = new Swagger\Client\Model\Dog($data); + $new_dog = new Model\Dog($data); // the property on the derived class should be set $this->assertSame('Great Dane', $new_dog->getBreed()); @@ -419,7 +435,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test if discriminator is initialized automatically public function testDiscriminatorInitialization() { - $new_dog = new Swagger\Client\Model\Dog(); + $new_dog = new Model\Dog(); $this->assertSame('Dog', $new_dog->getClassName()); } @@ -428,13 +444,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // create an AnimalFarm which is an object implementing the // ArrayAccess interface - $farm = new Swagger\Client\Model\AnimalFarm(); + $farm = new Model\AnimalFarm(); // add some animals to the farm to make sure the ArrayAccess // interface works - $farm[] = new Swagger\Client\Model\Dog(); - $farm[] = new Swagger\Client\Model\Cat(); - $farm[] = new Swagger\Client\Model\Animal(); + $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) @@ -455,16 +471,12 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // add some animals to the farm to make sure the ArrayAccess // interface works - $dog = new Swagger\Client\Model\Dog(); - $animal = new Swagger\Client\Model\Animal(); + $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()); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 7d7dcf3ede3..800cd512e4f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -1,34 +1,35 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setStatus("available"); // new tag - $tag= new Swagger\Client\Model\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 Swagger\Client\Model\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 Swagger\Client\Api\PetAPI(); + $pet_api = new Api\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -37,9 +38,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -55,9 +56,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventoryInObject() { // initialize the API client - //$config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient(); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + //$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient(); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventoryInObject(); @@ -65,8 +66,4 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase $this->assertInternalType("int", $get_response['available']); } */ - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 3efce8b08ba..a8487e58764 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -1,33 +1,34 @@ setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $user_api = new Swagger\Client\Api\UserApi($api_client); - // login - $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); - - $this->assertInternalType("string", $response); - $this->assertRegExp("/^logged in user session/", $response, "response string starts with 'logged in user session'"); - - } + // test login user + public function testLoginUser() + { + // initialize the API client + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $user_api = new Api\UserApi($api_client); + // login + $response = $user_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/client/petstore/python/.gitignore b/samples/client/petstore/python/.gitignore index 1dbc687de01..a655050c263 100644 --- a/samples/client/petstore/python/.gitignore +++ b/samples/client/petstore/python/.gitignore @@ -44,6 +44,8 @@ nosetests.xml coverage.xml *,cover .hypothesis/ +venv/ +.python-version # Translations *.mo diff --git a/samples/client/petstore/python/.swagger-codegen-ignore b/samples/client/petstore/python/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/python/.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 +# Thsi 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/python/LICENSE b/samples/client/petstore/python/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/python/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/python/Makefile b/samples/client/petstore/python/Makefile index 0f65e0c6ac3..52033cee703 100644 --- a/samples/client/petstore/python/Makefile +++ b/samples/client/petstore/python/Makefile @@ -15,7 +15,7 @@ clean: find . -name "__pycache__" -delete test: clean - bash ./test.sh + bash ./test_python2.sh test-all: clean - bash ./test-all.sh + bash ./test_python2_and_3.sh diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 3cdf5029787..8fc15c13eec 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -1,11 +1,11 @@ -# swagger_client -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +# petstore_api +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 Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-09T01:08:25.311+01:00 +- Build date: 2016-06-09T08:00:02.342+09:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -24,7 +24,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import swagger_client +import petstore_api ``` ### Setuptools @@ -38,7 +38,7 @@ python setup.py install --user Then import the package: ```python -import swagger_client +import petstore_api ``` ## Getting Started @@ -47,11 +47,11 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.FakeApi +api_instance = petstore_api.FakeApi number = 3.4 # float | None double = 1.2 # float | None string = 'string_example' # str | None @@ -66,7 +66,7 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) try: - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) except ApiException as e: print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e @@ -79,7 +79,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -104,17 +104,24 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) - [ApiResponse](docs/ApiResponse.md) + - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) - [FormatTest](docs/FormatTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) @@ -123,12 +130,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -138,6 +139,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ea12f270f02 --- /dev/null +++ b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_property** | **dict(str, str)** | | [optional] +**map_of_map_property** | [**dict(str, dict(str, str))**](dict.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/client/petstore/python/docs/Animal.md b/samples/client/petstore/python/docs/Animal.md index ceb8002b4ab..7ed4ba541fa 100644 --- a/samples/client/petstore/python/docs/Animal.md +++ b/samples/client/petstore/python/docs/Animal.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | +**color** | **str** | | [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/client/petstore/python/docs/AnimalFarm.md b/samples/client/petstore/python/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/python/docs/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/client/petstore/python/docs/ArrayTest.md b/samples/client/petstore/python/docs/ArrayTest.md new file mode 100644 index 00000000000..6ab0d137806 --- /dev/null +++ b/samples/client/petstore/python/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_of_string** | **list[str]** | | [optional] +**array_array_of_integer** | **list[list[int]]** | | [optional] +**array_array_of_model** | **list[list[ReadOnlyFirst]]** | | [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/python/docs/Cat.md b/samples/client/petstore/python/docs/Cat.md index fd4cd174fc2..d052c5615b8 100644 --- a/samples/client/petstore/python/docs/Cat.md +++ b/samples/client/petstore/python/docs/Cat.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | +**color** | **str** | | [optional] [default to 'red'] **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/client/petstore/python/docs/Dog.md b/samples/client/petstore/python/docs/Dog.md index a4b38a70335..ac70f17e668 100644 --- a/samples/client/petstore/python/docs/Dog.md +++ b/samples/client/petstore/python/docs/Dog.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | +**color** | **str** | | [optional] [default to 'red'] **breed** | **str** | | [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/python/docs/EnumClass.md b/samples/client/petstore/python/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/python/docs/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/client/petstore/python/docs/EnumTest.md b/samples/client/petstore/python/docs/EnumTest.md new file mode 100644 index 00000000000..38dd71f5b83 --- /dev/null +++ b/samples/client/petstore/python/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **str** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_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/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 66d9a04434a..16656613075 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -1,28 +1,28 @@ -# swagger_client.FakeApi +# petstore_api.FakeApi All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.FakeApi() +api_instance = petstore_api.FakeApi() number = 3.4 # float | None double = 1.2 # float | None string = 'string_example' # str | None @@ -37,7 +37,7 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) try: - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) except ApiException as e: print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e @@ -70,8 +70,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 [[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/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..b9808d5275e --- /dev/null +++ b/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **str** | | [optional] +**date_time** | **datetime** | | [optional] +**map** | [**dict(str, 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/client/petstore/python/docs/Name.md b/samples/client/petstore/python/docs/Name.md index a472a529a0f..542da3f0476 100644 --- a/samples/client/petstore/python/docs/Name.md +++ b/samples/client/petstore/python/docs/Name.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **name** | **int** | | **snake_case** | **int** | | [optional] **_property** | **str** | | [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/client/petstore/python/docs/PetApi.md b/samples/client/petstore/python/docs/PetApi.md index fb69778f611..109b264942f 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -1,4 +1,4 @@ -# swagger_client.PetApi +# petstore_api.PetApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,16 +24,16 @@ Add a new pet to the store ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() -body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store +api_instance = petstore_api.PetApi() +body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store try: # Add a new pet to the store @@ -73,15 +73,15 @@ Deletes a pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) @@ -124,15 +124,15 @@ Multiple status values can be provided with comma separated strings ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() status = ['status_example'] # list[str] | Status values that need to be considered for filter try: @@ -174,15 +174,15 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() tags = ['tags_example'] # list[str] | Tags to filter by try: @@ -224,17 +224,17 @@ Returns a single pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure API key authorization: api_key -swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' +petstore_api.configuration.api_key['api_key'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer' +# petstore_api.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet to return try: @@ -276,16 +276,16 @@ Update an existing pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() -body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store +api_instance = petstore_api.PetApi() +body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store try: # Update an existing pet @@ -325,15 +325,15 @@ Updates a pet in the store with form data ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet that needs to be updated name = 'name_example' # str | Updated name of the pet (optional) status = 'status_example' # str | Updated status of the pet (optional) @@ -378,15 +378,15 @@ uploads an image ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet to update additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) file = '/path/to/file.txt' # file | file to upload (optional) diff --git a/samples/client/petstore/python/docs/ReadOnlyFirst.md b/samples/client/petstore/python/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..93fed253d01 --- /dev/null +++ b/samples/client/petstore/python/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **str** | | [optional] +**baz** | **str** | | [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/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index 537009bde52..6b71a78659d 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -1,4 +1,4 @@ -# swagger_client.StoreApi +# petstore_api.StoreApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -20,12 +20,12 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted try: @@ -66,17 +66,17 @@ Returns a map of status codes to quantities ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure API key authorization: api_key -swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' +petstore_api.configuration.api_key['api_key'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer' +# petstore_api.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() try: # Returns pet inventories by status @@ -114,12 +114,12 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() order_id = 789 # int | ID of pet that needs to be fetched try: @@ -161,13 +161,13 @@ Place an order for a pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() -body = swagger_client.Order() # Order | order placed for purchasing the pet +api_instance = petstore_api.StoreApi() +body = petstore_api.Order() # Order | order placed for purchasing the pet try: # Place an order for a pet diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md index 1975c1fe7f3..4009418b13c 100644 --- a/samples/client/petstore/python/docs/UserApi.md +++ b/samples/client/petstore/python/docs/UserApi.md @@ -1,4 +1,4 @@ -# swagger_client.UserApi +# petstore_api.UserApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,13 +24,13 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = swagger_client.User() # User | Created user object +api_instance = petstore_api.UserApi() +body = petstore_api.User() # User | Created user object try: # Create user @@ -70,13 +70,13 @@ Creates list of users with given input array ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = [swagger_client.User()] # list[User] | List of user object +api_instance = petstore_api.UserApi() +body = [petstore_api.User()] # list[User] | List of user object try: # Creates list of users with given input array @@ -116,13 +116,13 @@ Creates list of users with given input array ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = [swagger_client.User()] # list[User] | List of user object +api_instance = petstore_api.UserApi() +body = [petstore_api.User()] # list[User] | List of user object try: # Creates list of users with given input array @@ -162,12 +162,12 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted try: @@ -208,12 +208,12 @@ Get user by user name ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. try: @@ -255,12 +255,12 @@ Logs user into the system ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The user name for login password = 'password_example' # str | The password for login in clear text @@ -304,12 +304,12 @@ Logs out current logged in user session ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() try: # Logs out current logged in user session @@ -346,14 +346,14 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted -body = swagger_client.User() # User | Updated user object +body = petstore_api.User() # User | Updated user object try: # Updated user diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py new file mode 100644 index 00000000000..ae225644f73 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -0,0 +1,61 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +# import models into sdk package +from .models.additional_properties_class import AdditionalPropertiesClass +from .models.animal import Animal +from .models.animal_farm import AnimalFarm +from .models.api_response import ApiResponse +from .models.array_test import ArrayTest +from .models.cat import Cat +from .models.category import Category +from .models.dog import Dog +from .models.enum_class import EnumClass +from .models.enum_test import EnumTest +from .models.format_test import FormatTest +from .models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from .models.model_200_response import Model200Response +from .models.model_return import ModelReturn +from .models.name import Name +from .models.order import Order +from .models.pet import Pet +from .models.read_only_first import ReadOnlyFirst +from .models.special_model_name import SpecialModelName +from .models.tag import Tag +from .models.user import User + +# import apis into sdk package +from .apis.fake_api import FakeApi +from .apis.pet_api import PetApi +from .apis.store_api import StoreApi +from .apis.user_api import UserApi + +# import ApiClient +from .api_client import ApiClient + +from .configuration import Configuration + +configuration = Configuration() diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py similarity index 99% rename from samples/client/petstore/python/swagger_client/api_client.py rename to samples/client/petstore/python/petstore_api/api_client.py index 5d5a5fccc4c..5bc448a950c 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -191,7 +191,7 @@ class ApiClient(object): :return: The serialized form of data. """ types = (str, int, float, bool, tuple) - if sys.version_info < (3,0): + if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): return None diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/petstore_api/apis/__init__.py similarity index 100% rename from samples/client/petstore/python/swagger_client/apis/__init__.py rename to samples/client/petstore/python/petstore_api/apis/__init__.py diff --git a/samples/client/petstore/python/swagger_client/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py similarity index 80% rename from samples/client/petstore/python/swagger_client/apis/fake_api.py rename to samples/client/petstore/python/petstore_api/apis/fake_api.py index 5d3903b2d21..317232217b8 100644 --- a/samples/client/petstore/python/swagger_client/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -1,20 +1,25 @@ # coding: utf-8 """ -FakeApi.py -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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. """ from __future__ import absolute_import @@ -48,8 +53,8 @@ class FakeApi(object): def test_endpoint_parameters(self, number, double, string, byte, **kwargs): """ - Fake endpoint for testing various parameters - Fake endpoint for testing various parameters + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function @@ -90,7 +95,6 @@ class FakeApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'number' is set if ('number' not in params) or (params['number'] is None): raise ValueError("Missing the required parameter `number` when calling `test_endpoint_parameters`") @@ -104,31 +108,30 @@ class FakeApi(object): if ('byte' not in params) or (params['byte'] is None): raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") - if 'number' in params and params['number'] > 543.2: + if 'number' in params and params['number'] > 543.2: raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") - if 'number' in params and params['number'] < 32.1: + if 'number' in params and params['number'] < 32.1: raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") - if 'double' in params and params['double'] > 123.4: + if 'double' in params and params['double'] > 123.4: raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") - if 'double' in params and params['double'] < 67.8: + if 'double' in params and params['double'] < 67.8: raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") - if 'integer' in params and params['integer'] > 100.0: + if 'integer' in params and params['integer'] > 100.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") - if 'integer' in params and params['integer'] < 10.0: + if 'integer' in params and params['integer'] < 10.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") - if 'int32' in params and params['int32'] > 200.0: + if 'int32' in params and params['int32'] > 200.0: raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") - if 'int32' in params and params['int32'] < 20.0: + if 'int32' in params and params['int32'] < 20.0: raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") - if 'float' in params and params['float'] > 987.6: + if 'float' in params and params['float'] > 987.6: raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") - if 'password' in params and len(params['password']) > 64: + if 'password' in params and len(params['password']) > 64: raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be less than or equal to `64`") - if 'password' in params and len(params['password']) < 10: + if 'password' in params and len(params['password']) < 10: raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") - resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -167,13 +170,13 @@ class FakeApi(object): # HTTP header `Accept` header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) + select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # Authentication setting auth_settings = [] diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py similarity index 96% rename from samples/client/petstore/python/swagger_client/apis/pet_api.py rename to samples/client/petstore/python/petstore_api/apis/pet_api.py index 3b6d9ba82fe..2f2ee4429c2 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -1,20 +1,25 @@ # coding: utf-8 """ -PetApi.py -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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. """ from __future__ import absolute_import @@ -79,12 +84,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") - resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -158,12 +161,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -238,12 +239,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'status' is set if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") - resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} @@ -316,12 +315,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'tags' is set if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") - resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} @@ -394,12 +391,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -472,12 +467,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") - resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -552,12 +545,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -636,12 +627,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") - resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py similarity index 92% rename from samples/client/petstore/python/swagger_client/apis/store_api.py rename to samples/client/petstore/python/petstore_api/apis/store_api.py index 352ab7eae63..e945b61509c 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -1,20 +1,25 @@ # coding: utf-8 """ -StoreApi.py -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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. """ from __future__ import absolute_import @@ -79,14 +84,12 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'order_id' is set if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") - if 'order_id' in params and params['order_id'] < 1.0: + if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `delete_order`, must be a value greater than or equal to `1.0`") - resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -159,8 +162,6 @@ class StoreApi(object): params[key] = val del params['kwargs'] - - resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -231,16 +232,14 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'order_id' is set if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - if 'order_id' in params and params['order_id'] > 5.0: + if 'order_id' in params and params['order_id'] > 5.0: raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") - if 'order_id' in params and params['order_id'] < 1.0: + if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") - resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -313,12 +312,10 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") - resource_path = '/store/order'.replace('{format}', 'json') path_params = {} diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py similarity index 96% rename from samples/client/petstore/python/swagger_client/apis/user_api.py rename to samples/client/petstore/python/petstore_api/apis/user_api.py index d5df6f0f541..5a8f1815495 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -1,20 +1,25 @@ # coding: utf-8 """ -UserApi.py -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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. """ from __future__ import absolute_import @@ -79,12 +84,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") - resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -157,12 +160,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") - resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -235,12 +236,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") - resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -313,12 +312,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") - resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -391,12 +388,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") - resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -470,7 +465,6 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `login_user`") @@ -478,7 +472,6 @@ class UserApi(object): if ('password' not in params) or (params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `login_user`") - resource_path = '/user/login'.replace('{format}', 'json') path_params = {} @@ -553,8 +546,6 @@ class UserApi(object): params[key] = val del params['kwargs'] - - resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -626,7 +617,6 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `update_user`") @@ -634,7 +624,6 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_user`") - resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py similarity index 85% rename from samples/client/petstore/python/swagger_client/configuration.py rename to samples/client/petstore/python/petstore_api/configuration.py index fe38630927e..76f1f57c784 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -33,6 +37,7 @@ import logging from six import iteritems + def singleton(cls, *args, **kw): instances = {} @@ -75,10 +80,9 @@ class Configuration(object): # access token for OAuth self.access_token = "" - # Logging Settings self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") + self.logger["package_logger"] = logging.getLogger("petstore_api") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' @@ -217,6 +221,14 @@ class Configuration(object): :return: The Auth Settings information dict. """ return { + + 'petstore_auth': + { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + }, 'api_key': { 'type': 'api_key', diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py new file mode 100644 index 00000000000..4ccf94c0415 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +# import models into model package +from .additional_properties_class import AdditionalPropertiesClass +from .animal import Animal +from .animal_farm import AnimalFarm +from .api_response import ApiResponse +from .array_test import ArrayTest +from .cat import Cat +from .category import Category +from .dog import Dog +from .enum_class import EnumClass +from .enum_test import EnumTest +from .format_test import FormatTest +from .mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from .model_200_response import Model200Response +from .model_return import ModelReturn +from .name import Name +from .order import Order +from .pet import Pet +from .read_only_first import ReadOnlyFirst +from .special_model_name import SpecialModelName +from .tag import Tag +from .user import User diff --git a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py new file mode 100644 index 00000000000..b5383efed38 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -0,0 +1,151 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class AdditionalPropertiesClass(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, map_property=None, map_of_map_property=None): + """ + AdditionalPropertiesClass - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'map_property': 'dict(str, str)', + 'map_of_map_property': 'dict(str, dict(str, str))' + } + + self.attribute_map = { + 'map_property': 'map_property', + 'map_of_map_property': 'map_of_map_property' + } + + self._map_property = map_property + self._map_of_map_property = map_of_map_property + + @property + def map_property(self): + """ + Gets the map_property of this AdditionalPropertiesClass. + + + :return: The map_property of this AdditionalPropertiesClass. + :rtype: dict(str, str) + """ + return self._map_property + + @map_property.setter + def map_property(self, map_property): + """ + Sets the map_property of this AdditionalPropertiesClass. + + + :param map_property: The map_property of this AdditionalPropertiesClass. + :type: dict(str, str) + """ + + self._map_property = map_property + + @property + def map_of_map_property(self): + """ + Gets the map_of_map_property of this AdditionalPropertiesClass. + + + :return: The map_of_map_property of this AdditionalPropertiesClass. + :rtype: dict(str, dict(str, str)) + """ + return self._map_of_map_property + + @map_of_map_property.setter + def map_of_map_property(self, map_of_map_property): + """ + Sets the map_of_map_property of this AdditionalPropertiesClass. + + + :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. + :type: dict(str, dict(str, str)) + """ + + self._map_of_map_property = map_of_map_property + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py similarity index 76% rename from samples/client/petstore/python/swagger_client/models/animal.py rename to samples/client/petstore/python/petstore_api/models/animal.py index 0ae8f2b4bde..8a5b6499872 100644 --- a/samples/client/petstore/python/swagger_client/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Animal(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red'): """ Animal - a model defined in Swagger @@ -38,14 +42,17 @@ class Animal(object): and the value is json key in definition. """ self.swagger_types = { - 'class_name': 'str' + 'class_name': 'str', + 'color': 'str' } self.attribute_map = { - 'class_name': 'className' + 'class_name': 'className', + 'color': 'color' } - self._class_name = None + self._class_name = class_name + self._color = color @property def class_name(self): @@ -67,9 +74,32 @@ class Animal(object): :param class_name: The class_name of this Animal. :type: str """ - + self._class_name = class_name + @property + def color(self): + """ + Gets the color of this Animal. + + + :return: The color of this Animal. + :rtype: str + """ + return self._color + + @color.setter + def color(self, color): + """ + Sets the color of this Animal. + + + :param color: The color of this Animal. + :type: str + """ + + self._color = color + def to_dict(self): """ Returns the model properties as a dict @@ -119,4 +149,3 @@ class Animal(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/petstore_api/models/animal_farm.py b/samples/client/petstore/python/petstore_api/models/animal_farm.py new file mode 100644 index 00000000000..72fce33f252 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/animal_farm.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class AnimalFarm(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + AnimalFarm - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + + } + + self.attribute_map = { + + } + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/api_response.py b/samples/client/petstore/python/petstore_api/models/api_response.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/api_response.py rename to samples/client/petstore/python/petstore_api/models/api_response.py index 918b4a98223..7cb5eb5c889 100644 --- a/samples/client/petstore/python/swagger_client/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class ApiResponse(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, code=None, type=None, message=None): """ ApiResponse - a model defined in Swagger @@ -49,9 +53,9 @@ class ApiResponse(object): 'message': 'message' } - self._code = None - self._type = None - self._message = None + self._code = code + self._type = type + self._message = message @property def code(self): @@ -73,7 +77,7 @@ class ApiResponse(object): :param code: The code of this ApiResponse. :type: int """ - + self._code = code @property @@ -96,7 +100,7 @@ class ApiResponse(object): :param type: The type of this ApiResponse. :type: str """ - + self._type = type @property @@ -119,7 +123,7 @@ class ApiResponse(object): :param message: The message of this ApiResponse. :type: str """ - + self._message = message def to_dict(self): @@ -171,4 +175,3 @@ class ApiResponse(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/petstore_api/models/array_test.py b/samples/client/petstore/python/petstore_api/models/array_test.py new file mode 100644 index 00000000000..adaeecc2ed7 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class ArrayTest(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): + """ + ArrayTest - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'array_of_string': 'list[str]', + 'array_array_of_integer': 'list[list[int]]', + 'array_array_of_model': 'list[list[ReadOnlyFirst]]' + } + + self.attribute_map = { + 'array_of_string': 'array_of_string', + 'array_array_of_integer': 'array_array_of_integer', + 'array_array_of_model': 'array_array_of_model' + } + + self._array_of_string = array_of_string + self._array_array_of_integer = array_array_of_integer + self._array_array_of_model = array_array_of_model + + @property + def array_of_string(self): + """ + Gets the array_of_string of this ArrayTest. + + + :return: The array_of_string of this ArrayTest. + :rtype: list[str] + """ + return self._array_of_string + + @array_of_string.setter + def array_of_string(self, array_of_string): + """ + Sets the array_of_string of this ArrayTest. + + + :param array_of_string: The array_of_string of this ArrayTest. + :type: list[str] + """ + + self._array_of_string = array_of_string + + @property + def array_array_of_integer(self): + """ + Gets the array_array_of_integer of this ArrayTest. + + + :return: The array_array_of_integer of this ArrayTest. + :rtype: list[list[int]] + """ + return self._array_array_of_integer + + @array_array_of_integer.setter + def array_array_of_integer(self, array_array_of_integer): + """ + Sets the array_array_of_integer of this ArrayTest. + + + :param array_array_of_integer: The array_array_of_integer of this ArrayTest. + :type: list[list[int]] + """ + + self._array_array_of_integer = array_array_of_integer + + @property + def array_array_of_model(self): + """ + Gets the array_array_of_model of this ArrayTest. + + + :return: The array_array_of_model of this ArrayTest. + :rtype: list[list[ReadOnlyFirst]] + """ + return self._array_array_of_model + + @array_array_of_model.setter + def array_array_of_model(self, array_array_of_model): + """ + Sets the array_array_of_model of this ArrayTest. + + + :param array_array_of_model: The array_array_of_model of this ArrayTest. + :type: list[list[ReadOnlyFirst]] + """ + + self._array_array_of_model = array_array_of_model + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py similarity index 79% rename from samples/client/petstore/python/swagger_client/models/cat.py rename to samples/client/petstore/python/petstore_api/models/cat.py index fd2e5e4fce4..a37e0b0674b 100644 --- a/samples/client/petstore/python/swagger_client/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Cat(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red', declawed=None): """ Cat - a model defined in Swagger @@ -39,16 +43,19 @@ class Cat(object): """ self.swagger_types = { 'class_name': 'str', + 'color': 'str', 'declawed': 'bool' } self.attribute_map = { 'class_name': 'className', + 'color': 'color', 'declawed': 'declawed' } - self._class_name = None - self._declawed = None + self._class_name = class_name + self._color = color + self._declawed = declawed @property def class_name(self): @@ -70,9 +77,32 @@ class Cat(object): :param class_name: The class_name of this Cat. :type: str """ - + self._class_name = class_name + @property + def color(self): + """ + Gets the color of this Cat. + + + :return: The color of this Cat. + :rtype: str + """ + return self._color + + @color.setter + def color(self, color): + """ + Sets the color of this Cat. + + + :param color: The color of this Cat. + :type: str + """ + + self._color = color + @property def declawed(self): """ @@ -93,7 +123,7 @@ class Cat(object): :param declawed: The declawed of this Cat. :type: bool """ - + self._declawed = declawed def to_dict(self): @@ -145,4 +175,3 @@ class Cat(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/category.py rename to samples/client/petstore/python/petstore_api/models/category.py index e4f4a993cab..9adf7e1bab2 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Category(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, name=None): """ Category - a model defined in Swagger @@ -47,8 +51,8 @@ class Category(object): 'name': 'name' } - self._id = None - self._name = None + self._id = id + self._name = name @property def id(self): @@ -70,7 +74,7 @@ class Category(object): :param id: The id of this Category. :type: int """ - + self._id = id @property @@ -93,7 +97,7 @@ class Category(object): :param name: The name of this Category. :type: str """ - + self._name = name def to_dict(self): @@ -145,4 +149,3 @@ class Category(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py similarity index 79% rename from samples/client/petstore/python/swagger_client/models/dog.py rename to samples/client/petstore/python/petstore_api/models/dog.py index ac25ef01807..70225244a13 100644 --- a/samples/client/petstore/python/swagger_client/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Dog(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red', breed=None): """ Dog - a model defined in Swagger @@ -39,16 +43,19 @@ class Dog(object): """ self.swagger_types = { 'class_name': 'str', + 'color': 'str', 'breed': 'str' } self.attribute_map = { 'class_name': 'className', + 'color': 'color', 'breed': 'breed' } - self._class_name = None - self._breed = None + self._class_name = class_name + self._color = color + self._breed = breed @property def class_name(self): @@ -70,9 +77,32 @@ class Dog(object): :param class_name: The class_name of this Dog. :type: str """ - + self._class_name = class_name + @property + def color(self): + """ + Gets the color of this Dog. + + + :return: The color of this Dog. + :rtype: str + """ + return self._color + + @color.setter + def color(self, color): + """ + Sets the color of this Dog. + + + :param color: The color of this Dog. + :type: str + """ + + self._color = color + @property def breed(self): """ @@ -93,7 +123,7 @@ class Dog(object): :param breed: The breed of this Dog. :type: str """ - + self._breed = breed def to_dict(self): @@ -145,4 +175,3 @@ class Dog(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/petstore_api/models/enum_class.py b/samples/client/petstore/python/petstore_api/models/enum_class.py new file mode 100644 index 00000000000..ec78827141b --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/enum_class.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class EnumClass(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + EnumClass - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + + } + + self.attribute_map = { + + } + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py new file mode 100644 index 00000000000..faf89659ef2 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -0,0 +1,195 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class EnumTest(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, enum_string=None, enum_integer=None, enum_number=None): + """ + EnumTest - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'enum_string': 'str', + 'enum_integer': 'int', + 'enum_number': 'float' + } + + self.attribute_map = { + 'enum_string': 'enum_string', + 'enum_integer': 'enum_integer', + 'enum_number': 'enum_number' + } + + self._enum_string = enum_string + self._enum_integer = enum_integer + self._enum_number = enum_number + + @property + def enum_string(self): + """ + Gets the enum_string of this EnumTest. + + + :return: The enum_string of this EnumTest. + :rtype: str + """ + return self._enum_string + + @enum_string.setter + def enum_string(self, enum_string): + """ + Sets the enum_string of this EnumTest. + + + :param enum_string: The enum_string of this EnumTest. + :type: str + """ + allowed_values = ["UPPER", "lower"] + if enum_string not in allowed_values: + raise ValueError( + "Invalid value for `enum_string`, must be one of {0}" + .format(allowed_values) + ) + + self._enum_string = enum_string + + @property + def enum_integer(self): + """ + Gets the enum_integer of this EnumTest. + + + :return: The enum_integer of this EnumTest. + :rtype: int + """ + return self._enum_integer + + @enum_integer.setter + def enum_integer(self, enum_integer): + """ + Sets the enum_integer of this EnumTest. + + + :param enum_integer: The enum_integer of this EnumTest. + :type: int + """ + allowed_values = ["1", "-1"] + if enum_integer not in allowed_values: + raise ValueError( + "Invalid value for `enum_integer`, must be one of {0}" + .format(allowed_values) + ) + + self._enum_integer = enum_integer + + @property + def enum_number(self): + """ + Gets the enum_number of this EnumTest. + + + :return: The enum_number of this EnumTest. + :rtype: float + """ + return self._enum_number + + @enum_number.setter + def enum_number(self, enum_number): + """ + Sets the enum_number of this EnumTest. + + + :param enum_number: The enum_number of this EnumTest. + :type: float + """ + allowed_values = ["1.1", "-1.2"] + if enum_number not in allowed_values: + raise ValueError( + "Invalid value for `enum_number`, must be one of {0}" + .format(allowed_values) + ) + + self._enum_number = enum_number + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/format_test.py rename to samples/client/petstore/python/petstore_api/models/format_test.py index 7fce3351dd4..54522805164 100644 --- a/samples/client/petstore/python/swagger_client/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class FormatTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, integer=None, int32=None, int64=None, number=None, float=None, double=None, string=None, byte=None, binary=None, date=None, date_time=None, uuid=None, password=None): """ FormatTest - a model defined in Swagger @@ -69,19 +73,19 @@ class FormatTest(object): 'password': 'password' } - self._integer = None - self._int32 = None - self._int64 = None - self._number = None - self._float = None - self._double = None - self._string = None - self._byte = None - self._binary = None - self._date = None - self._date_time = None - self._uuid = None - self._password = None + 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._date_time = date_time + self._uuid = uuid + self._password = password @property def integer(self): @@ -103,12 +107,12 @@ class FormatTest(object): :param integer: The integer of this FormatTest. :type: int """ - + if not integer: raise ValueError("Invalid value for `integer`, must not be `None`") - if integer > 100.0: + if integer > 100.0: raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") - if integer < 10.0: + if integer < 10.0: raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") self._integer = integer @@ -133,12 +137,12 @@ class FormatTest(object): :param int32: The int32 of this FormatTest. :type: int """ - + if not int32: raise ValueError("Invalid value for `int32`, must not be `None`") - if int32 > 200.0: + if int32 > 200.0: raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") - if int32 < 20.0: + if int32 < 20.0: raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") self._int32 = int32 @@ -163,7 +167,7 @@ class FormatTest(object): :param int64: The int64 of this FormatTest. :type: int """ - + self._int64 = int64 @property @@ -186,12 +190,12 @@ class FormatTest(object): :param number: The number of this FormatTest. :type: float """ - + if not number: raise ValueError("Invalid value for `number`, must not be `None`") - if number > 543.2: + if number > 543.2: raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") - if number < 32.1: + if number < 32.1: raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") self._number = number @@ -216,12 +220,12 @@ class FormatTest(object): :param float: The float of this FormatTest. :type: float """ - + if not float: raise ValueError("Invalid value for `float`, must not be `None`") - if float > 987.6: + if float > 987.6: raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") - if float < 54.3: + if float < 54.3: raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") self._float = float @@ -246,12 +250,12 @@ class FormatTest(object): :param double: The double of this FormatTest. :type: float """ - + if not double: raise ValueError("Invalid value for `double`, must not be `None`") - if double > 123.4: + if double > 123.4: raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") - if double < 67.8: + if double < 67.8: raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") self._double = double @@ -276,10 +280,10 @@ class FormatTest(object): :param string: The string of this FormatTest. :type: str """ - + if not string: raise ValueError("Invalid value for `string`, must not be `None`") - if not re.search('[a-z]', string, flags=re.IGNORECASE): + if not re.search('[a-z]', string, flags=re.IGNORECASE): raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") self._string = string @@ -304,7 +308,7 @@ class FormatTest(object): :param byte: The byte of this FormatTest. :type: str """ - + self._byte = byte @property @@ -327,7 +331,7 @@ class FormatTest(object): :param binary: The binary of this FormatTest. :type: str """ - + self._binary = binary @property @@ -350,7 +354,7 @@ class FormatTest(object): :param date: The date of this FormatTest. :type: date """ - + self._date = date @property @@ -373,7 +377,7 @@ class FormatTest(object): :param date_time: The date_time of this FormatTest. :type: datetime """ - + self._date_time = date_time @property @@ -396,7 +400,7 @@ class FormatTest(object): :param uuid: The uuid of this FormatTest. :type: str """ - + self._uuid = uuid @property @@ -419,12 +423,12 @@ class FormatTest(object): :param password: The password of this FormatTest. :type: str """ - + if not password: raise ValueError("Invalid value for `password`, must not be `None`") - if len(password) > 64: + if len(password) > 64: raise ValueError("Invalid value for `password`, length must be less than `64`") - if len(password) < 10: + if len(password) < 10: raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") self._password = password @@ -478,4 +482,3 @@ class FormatTest(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py new file mode 100644 index 00000000000..9c4bdd2a851 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class MixedPropertiesAndAdditionalPropertiesClass(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, uuid=None, date_time=None, map=None): + """ + MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'uuid': 'str', + 'date_time': 'datetime', + 'map': 'dict(str, Animal)' + } + + self.attribute_map = { + 'uuid': 'uuid', + 'date_time': 'dateTime', + 'map': 'map' + } + + self._uuid = uuid + self._date_time = date_time + self._map = map + + @property + def uuid(self): + """ + Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + + :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + :rtype: str + """ + return self._uuid + + @uuid.setter + def uuid(self, uuid): + """ + Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + + :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + :type: str + """ + + self._uuid = uuid + + @property + def date_time(self): + """ + Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + + :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + :rtype: datetime + """ + return self._date_time + + @date_time.setter + def date_time(self, date_time): + """ + Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + + :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + :type: datetime + """ + + self._date_time = date_time + + @property + def map(self): + """ + Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. + + + :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. + :rtype: dict(str, Animal) + """ + return self._map + + @map.setter + def map(self, map): + """ + Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. + + + :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. + :type: dict(str, Animal) + """ + + self._map = map + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/model_200_response.py b/samples/client/petstore/python/petstore_api/models/model_200_response.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/model_200_response.py rename to samples/client/petstore/python/petstore_api/models/model_200_response.py index f99847cbdd5..95326567ada 100644 --- a/samples/client/petstore/python/swagger_client/models/model_200_response.py +++ b/samples/client/petstore/python/petstore_api/models/model_200_response.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Model200Response(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, name=None): """ Model200Response - a model defined in Swagger @@ -45,7 +49,7 @@ class Model200Response(object): 'name': 'name' } - self._name = None + self._name = name @property def name(self): @@ -67,7 +71,7 @@ class Model200Response(object): :param name: The name of this Model200Response. :type: int """ - + self._name = name def to_dict(self): @@ -119,4 +123,3 @@ class Model200Response(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/model_return.py b/samples/client/petstore/python/petstore_api/models/model_return.py similarity index 88% rename from samples/client/petstore/python/swagger_client/models/model_return.py rename to samples/client/petstore/python/petstore_api/models/model_return.py index 8228f41943c..5587c068b0f 100644 --- a/samples/client/petstore/python/swagger_client/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class ModelReturn(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, _return=None): """ ModelReturn - a model defined in Swagger @@ -45,7 +49,7 @@ class ModelReturn(object): '_return': 'return' } - self.__return = None + self.__return = _return @property def _return(self): @@ -67,7 +71,7 @@ class ModelReturn(object): :param _return: The _return of this ModelReturn. :type: int """ - + self.__return = _return def to_dict(self): @@ -119,4 +123,3 @@ class ModelReturn(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py similarity index 82% rename from samples/client/petstore/python/swagger_client/models/name.py rename to samples/client/petstore/python/petstore_api/models/name.py index 51345d131ff..fa489658960 100644 --- a/samples/client/petstore/python/swagger_client/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Name(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, name=None, _property=None): """ Name - a model defined in Swagger @@ -40,18 +44,21 @@ class Name(object): self.swagger_types = { 'name': 'int', 'snake_case': 'int', - '_property': 'str' + '_property': 'str', + '_123_number': 'int' } self.attribute_map = { 'name': 'name', 'snake_case': 'snake_case', - '_property': 'property' + '_property': 'property', + '_123_number': '123Number' } - self._name = None self._snake_case = None - self.__property = None + self.__123_number = None + self._name = name + self.__property = _property @property def name(self): @@ -73,7 +80,7 @@ class Name(object): :param name: The name of this Name. :type: int """ - + self._name = name @property @@ -87,18 +94,6 @@ class Name(object): """ return self._snake_case - @snake_case.setter - def snake_case(self, snake_case): - """ - Sets the snake_case of this Name. - - - :param snake_case: The snake_case of this Name. - :type: int - """ - - self._snake_case = snake_case - @property def _property(self): """ @@ -119,9 +114,20 @@ class Name(object): :param _property: The _property of this Name. :type: str """ - + self.__property = _property + @property + def _123_number(self): + """ + Gets the _123_number of this Name. + + + :return: The _123_number of this Name. + :rtype: int + """ + return self.__123_number + def to_dict(self): """ Returns the model properties as a dict @@ -171,4 +177,3 @@ class Name(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py similarity index 90% rename from samples/client/petstore/python/swagger_client/models/order.py rename to samples/client/petstore/python/petstore_api/models/order.py index 07f2c627d91..98d36719006 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Order(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): """ Order - a model defined in Swagger @@ -55,12 +59,12 @@ class Order(object): 'complete': 'complete' } - self._id = None - self._pet_id = None - self._quantity = None - self._ship_date = None - self._status = None - self._complete = False + self._id = id + self._pet_id = pet_id + self._quantity = quantity + self._ship_date = ship_date + self._status = status + self._complete = complete @property def id(self): @@ -82,7 +86,7 @@ class Order(object): :param id: The id of this Order. :type: int """ - + self._id = id @property @@ -105,7 +109,7 @@ class Order(object): :param pet_id: The pet_id of this Order. :type: int """ - + self._pet_id = pet_id @property @@ -128,7 +132,7 @@ class Order(object): :param quantity: The quantity of this Order. :type: int """ - + self._quantity = quantity @property @@ -151,7 +155,7 @@ class Order(object): :param ship_date: The ship_date of this Order. :type: datetime """ - + self._ship_date = ship_date @property @@ -203,7 +207,7 @@ class Order(object): :param complete: The complete of this Order. :type: bool """ - + self._complete = complete def to_dict(self): @@ -255,4 +259,3 @@ class Order(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py similarity index 90% rename from samples/client/petstore/python/swagger_client/models/pet.py rename to samples/client/petstore/python/petstore_api/models/pet.py index 60f762238f3..7a93da19db9 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Pet(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): """ Pet - a model defined in Swagger @@ -55,12 +59,12 @@ class Pet(object): 'status': 'status' } - self._id = None - self._category = None - self._name = None - self._photo_urls = None - self._tags = None - self._status = None + self._id = id + self._category = category + self._name = name + self._photo_urls = photo_urls + self._tags = tags + self._status = status @property def id(self): @@ -82,7 +86,7 @@ class Pet(object): :param id: The id of this Pet. :type: int """ - + self._id = id @property @@ -105,7 +109,7 @@ class Pet(object): :param category: The category of this Pet. :type: Category """ - + self._category = category @property @@ -128,7 +132,7 @@ class Pet(object): :param name: The name of this Pet. :type: str """ - + self._name = name @property @@ -151,7 +155,7 @@ class Pet(object): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ - + self._photo_urls = photo_urls @property @@ -174,7 +178,7 @@ class Pet(object): :param tags: The tags of this Pet. :type: list[Tag] """ - + self._tags = tags @property @@ -255,4 +259,3 @@ class Pet(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/petstore_api/models/read_only_first.py b/samples/client/petstore/python/petstore_api/models/read_only_first.py new file mode 100644 index 00000000000..c04d52501cf --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/read_only_first.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from pprint import pformat +from six import iteritems +import re + + +class ReadOnlyFirst(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, baz=None): + """ + ReadOnlyFirst - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'bar': 'str', + 'baz': 'str' + } + + self.attribute_map = { + 'bar': 'bar', + 'baz': 'baz' + } + + self._bar = None + self._baz = baz + + @property + def bar(self): + """ + Gets the bar of this ReadOnlyFirst. + + + :return: The bar of this ReadOnlyFirst. + :rtype: str + """ + return self._bar + + @property + def baz(self): + """ + Gets the baz of this ReadOnlyFirst. + + + :return: The baz of this ReadOnlyFirst. + :rtype: str + """ + return self._baz + + @baz.setter + def baz(self, baz): + """ + Sets the baz of this ReadOnlyFirst. + + + :param baz: The baz of this ReadOnlyFirst. + :type: str + """ + + self._baz = baz + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/swagger_client/models/special_model_name.py b/samples/client/petstore/python/petstore_api/models/special_model_name.py similarity index 88% rename from samples/client/petstore/python/swagger_client/models/special_model_name.py rename to samples/client/petstore/python/petstore_api/models/special_model_name.py index 3e45c0e4496..e48b7d79faf 100644 --- a/samples/client/petstore/python/swagger_client/models/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/models/special_model_name.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class SpecialModelName(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, special_property_name=None): """ SpecialModelName - a model defined in Swagger @@ -45,7 +49,7 @@ class SpecialModelName(object): 'special_property_name': '$special[property.name]' } - self._special_property_name = None + self._special_property_name = special_property_name @property def special_property_name(self): @@ -67,7 +71,7 @@ class SpecialModelName(object): :param special_property_name: The special_property_name of this SpecialModelName. :type: int """ - + self._special_property_name = special_property_name def to_dict(self): @@ -119,4 +123,3 @@ class SpecialModelName(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/tag.py rename to samples/client/petstore/python/petstore_api/models/tag.py index f09a4c36df3..95013b4fa8a 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class Tag(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, name=None): """ Tag - a model defined in Swagger @@ -47,8 +51,8 @@ class Tag(object): 'name': 'name' } - self._id = None - self._name = None + self._id = id + self._name = name @property def id(self): @@ -70,7 +74,7 @@ class Tag(object): :param id: The id of this Tag. :type: int """ - + self._id = id @property @@ -93,7 +97,7 @@ class Tag(object): :param name: The name of this Tag. :type: str """ - + self._name = name def to_dict(self): @@ -145,4 +149,3 @@ class Tag(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py similarity index 89% rename from samples/client/petstore/python/swagger_client/models/user.py rename to samples/client/petstore/python/petstore_api/models/user.py index 87d132a5037..1caf604d825 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +20,6 @@ Copyright 2016 SmartBear Software 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. - - Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -28,7 +32,7 @@ class User(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): """ User - a model defined in Swagger @@ -59,14 +63,14 @@ class User(object): 'user_status': 'userStatus' } - self._id = None - self._username = None - self._first_name = None - self._last_name = None - self._email = None - self._password = None - self._phone = None - self._user_status = None + self._id = id + self._username = username + self._first_name = first_name + self._last_name = last_name + self._email = email + self._password = password + self._phone = phone + self._user_status = user_status @property def id(self): @@ -88,7 +92,7 @@ class User(object): :param id: The id of this User. :type: int """ - + self._id = id @property @@ -111,7 +115,7 @@ class User(object): :param username: The username of this User. :type: str """ - + self._username = username @property @@ -134,7 +138,7 @@ class User(object): :param first_name: The first_name of this User. :type: str """ - + self._first_name = first_name @property @@ -157,7 +161,7 @@ class User(object): :param last_name: The last_name of this User. :type: str """ - + self._last_name = last_name @property @@ -180,7 +184,7 @@ class User(object): :param email: The email of this User. :type: str """ - + self._email = email @property @@ -203,7 +207,7 @@ class User(object): :param password: The password of this User. :type: str """ - + self._password = password @property @@ -226,7 +230,7 @@ class User(object): :param phone: The phone of this User. :type: str """ - + self._phone = phone @property @@ -249,7 +253,7 @@ class User(object): :param user_status: The user_status of this User. :type: int """ - + self._user_status = user_status def to_dict(self): @@ -301,4 +305,3 @@ class User(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/petstore_api/rest.py similarity index 94% rename from samples/client/petstore/python/swagger_client/rest.py rename to samples/client/petstore/python/petstore_api/rest.py index 352bb503ac5..d27f1652706 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -1,7 +1,13 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + 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 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +20,8 @@ Copyright 2016 SmartBear Software 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. - -Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: -https://www.dropbox.com/developers/core/sdks/python """ + from __future__ import absolute_import import sys @@ -138,8 +142,11 @@ class RESTClientObject(object): if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': + request_body = None + if body: + request_body = json.dumps(body) r = self.pool_manager.request(method, url, - body=json.dumps(body), + body=request_body, headers=headers) if headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, diff --git a/samples/client/petstore/python/pom.xml b/samples/client/petstore/python/pom.xml index 147938617d2..6eaa49eaea9 100644 --- a/samples/client/petstore/python/pom.xml +++ b/samples/client/petstore/python/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - com.wordnik + io.swagger PythonPetstoreClientTests pom 1.0-SNAPSHOT @@ -35,7 +35,7 @@ make - test + test-all diff --git a/samples/client/petstore/python/requirements.txt b/samples/client/petstore/python/requirements.txt new file mode 100644 index 00000000000..f00e08fa339 --- /dev/null +++ b/samples/client/petstore/python/requirements.txt @@ -0,0 +1,5 @@ +certifi >= 14.05.14 +six == 1.8.0 +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.15.1 diff --git a/samples/client/petstore/python/setup.cfg b/samples/client/petstore/python/setup.cfg index c9eef8726d6..26b7a359d58 100644 --- a/samples/client/petstore/python/setup.cfg +++ b/samples/client/petstore/python/setup.cfg @@ -4,7 +4,7 @@ verbosity=2 randomize=true exe=true with-coverage=true -cover-package=swagger_client +cover-package=petstore_api cover-erase=true [flake8] diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index 577fd8133bf..b15651ff2b5 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -1,13 +1,33 @@ # coding: utf-8 +""" + 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 + + 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. +""" + import sys from setuptools import setup, find_packages -NAME = "swagger_client" +NAME = "petstore_api" VERSION = "1.0.0" - - # To install the library, run the following # # python setup.py install @@ -28,8 +48,6 @@ setup( packages=find_packages(), include_package_data=True, long_description="""\ - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ """ ) - - diff --git a/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO b/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO deleted file mode 100644 index a4852b36ea4..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO +++ /dev/null @@ -1,12 +0,0 @@ -Metadata-Version: 1.0 -Name: swagger-client -Version: 1.0.0 -Summary: Swagger Petstore -Home-page: UNKNOWN -Author: UNKNOWN -Author-email: apiteam@swagger.io -License: UNKNOWN -Description: This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. - -Keywords: Swagger,Swagger Petstore -Platform: UNKNOWN diff --git a/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt b/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/samples/client/petstore/python/swagger_client.egg-info/requires.txt b/samples/client/petstore/python/swagger_client.egg-info/requires.txt deleted file mode 100644 index 86355123cff..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/requires.txt +++ /dev/null @@ -1,4 +0,0 @@ -urllib3 >= 1.15 -six >= 1.10 -certifi -python-dateutil diff --git a/samples/client/petstore/python/swagger_client.egg-info/top_level.txt b/samples/client/petstore/python/swagger_client.egg-info/top_level.txt deleted file mode 100644 index 01f6691e7ca..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/top_level.txt +++ /dev/null @@ -1,3 +0,0 @@ -swagger_client -test -tests diff --git a/samples/client/petstore/python/swagger_client/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py deleted file mode 100644 index 783f8b9713a..00000000000 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -from __future__ import absolute_import - -# import models into sdk package -from .models.animal import Animal -from .models.api_response import ApiResponse -from .models.cat import Cat -from .models.category import Category -from .models.dog import Dog -from .models.format_test import FormatTest -from .models.model_200_response import Model200Response -from .models.model_return import ModelReturn -from .models.name import Name -from .models.order import Order -from .models.pet import Pet -from .models.special_model_name import SpecialModelName -from .models.tag import Tag -from .models.user import User - -# import apis into sdk package -from .apis.fake_api import FakeApi -from .apis.pet_api import PetApi -from .apis.store_api import StoreApi -from .apis.user_api import UserApi - -# import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration - -configuration = Configuration() diff --git a/samples/client/petstore/python/swagger_client/models/__init__.py b/samples/client/petstore/python/swagger_client/models/__init__.py deleted file mode 100644 index 1d0e82f2295..00000000000 --- a/samples/client/petstore/python/swagger_client/models/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -from __future__ import absolute_import - -# import models into model package -from .animal import Animal -from .api_response import ApiResponse -from .cat import Cat -from .category import Category -from .dog import Dog -from .format_test import FormatTest -from .model_200_response import Model200Response -from .model_return import ModelReturn -from .name import Name -from .order import Order -from .pet import Pet -from .special_model_name import SpecialModelName -from .tag import Tag -from .user import User diff --git a/samples/client/petstore/python/swagger_client/models/inline_response_200.py b/samples/client/petstore/python/swagger_client/models/inline_response_200.py deleted file mode 100644 index f55ff5ee4d5..00000000000 --- a/samples/client/petstore/python/swagger_client/models/inline_response_200.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding: utf-8 - -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - Ref: https://github.com/swagger-api/swagger-codegen -""" - -from pprint import pformat -from six import iteritems - - -class InlineResponse200(object): - """ - NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - def __init__(self): - """ - InlineResponse200 - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'tags': 'list[Tag]', - 'id': 'int', - 'category': 'object', - 'status': 'str', - 'name': 'str', - 'photo_urls': 'list[str]' - } - - self.attribute_map = { - 'tags': 'tags', - 'id': 'id', - 'category': 'category', - 'status': 'status', - 'name': 'name', - 'photo_urls': 'photoUrls' - } - - self._tags = None - self._id = None - self._category = None - self._status = None - self._name = None - self._photo_urls = None - - @property - def tags(self): - """ - Gets the tags of this InlineResponse200. - - - :return: The tags of this InlineResponse200. - :rtype: list[Tag] - """ - return self._tags - - @tags.setter - def tags(self, tags): - """ - Sets the tags of this InlineResponse200. - - - :param tags: The tags of this InlineResponse200. - :type: list[Tag] - """ - self._tags = tags - - @property - def id(self): - """ - Gets the id of this InlineResponse200. - - - :return: The id of this InlineResponse200. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """ - Sets the id of this InlineResponse200. - - - :param id: The id of this InlineResponse200. - :type: int - """ - self._id = id - - @property - def category(self): - """ - Gets the category of this InlineResponse200. - - - :return: The category of this InlineResponse200. - :rtype: object - """ - return self._category - - @category.setter - def category(self, category): - """ - Sets the category of this InlineResponse200. - - - :param category: The category of this InlineResponse200. - :type: object - """ - self._category = category - - @property - def status(self): - """ - Gets the status of this InlineResponse200. - pet status in the store - - :return: The status of this InlineResponse200. - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """ - Sets the status of this InlineResponse200. - pet status in the store - - :param status: The status of this InlineResponse200. - :type: str - """ - allowed_values = ["available", "pending", "sold"] - if status not in allowed_values: - raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) - ) - self._status = status - - @property - def name(self): - """ - Gets the name of this InlineResponse200. - - - :return: The name of this InlineResponse200. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """ - Sets the name of this InlineResponse200. - - - :param name: The name of this InlineResponse200. - :type: str - """ - self._name = name - - @property - def photo_urls(self): - """ - Gets the photo_urls of this InlineResponse200. - - - :return: The photo_urls of this InlineResponse200. - :rtype: list[str] - """ - return self._photo_urls - - @photo_urls.setter - def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this InlineResponse200. - - - :param photo_urls: The photo_urls of this InlineResponse200. - :type: list[str] - """ - self._photo_urls = photo_urls - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other - diff --git a/samples/client/petstore/python/test-requirements.txt b/samples/client/petstore/python/test-requirements.txt new file mode 100644 index 00000000000..2702246c0e6 --- /dev/null +++ b/samples/client/petstore/python/test-requirements.txt @@ -0,0 +1,5 @@ +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/samples/client/petstore/python/test/test_additional_properties_class.py b/samples/client/petstore/python/test/test_additional_properties_class.py new file mode 100644 index 00000000000..de3d2bcd8b6 --- /dev/null +++ b/samples/client/petstore/python/test/test_additional_properties_class.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass + + +class TestAdditionalPropertiesClass(unittest.TestCase): + """ AdditionalPropertiesClass unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesClass(self): + """ + Test AdditionalPropertiesClass + """ + model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_animal.py b/samples/client/petstore/python/test/test_animal.py index 279ed1850dd..7db98a10170 100644 --- a/samples/client/petstore/python/test/test_animal.py +++ b/samples/client/petstore/python/test/test_animal.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.animal import Animal +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.animal import Animal class TestAnimal(unittest.TestCase): @@ -42,8 +46,8 @@ class TestAnimal(unittest.TestCase): """ Test Animal """ - model = swagger_client.models.animal.Animal() + model = petstore_api.models.animal.Animal() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_animal_farm.py b/samples/client/petstore/python/test/test_animal_farm.py new file mode 100644 index 00000000000..e4ecbf50478 --- /dev/null +++ b/samples/client/petstore/python/test/test_animal_farm.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.animal_farm import AnimalFarm + + +class TestAnimalFarm(unittest.TestCase): + """ AnimalFarm unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAnimalFarm(self): + """ + Test AnimalFarm + """ + model = petstore_api.models.animal_farm.AnimalFarm() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_api_response.py b/samples/client/petstore/python/test/test_api_response.py index be73dbf373d..9c62f641cd7 100644 --- a/samples/client/petstore/python/test/test_api_response.py +++ b/samples/client/petstore/python/test/test_api_response.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.api_response import ApiResponse +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.api_response import ApiResponse class TestApiResponse(unittest.TestCase): @@ -42,8 +46,8 @@ class TestApiResponse(unittest.TestCase): """ Test ApiResponse """ - model = swagger_client.models.api_response.ApiResponse() + model = petstore_api.models.api_response.ApiResponse() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_array_test.py b/samples/client/petstore/python/test/test_array_test.py new file mode 100644 index 00000000000..a5509779cc5 --- /dev/null +++ b/samples/client/petstore/python/test/test_array_test.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.array_test import ArrayTest + + +class TestArrayTest(unittest.TestCase): + """ ArrayTest unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayTest(self): + """ + Test ArrayTest + """ + model = petstore_api.models.array_test.ArrayTest() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_cat.py b/samples/client/petstore/python/test/test_cat.py index 728a824fa5b..3a9f7f1b75d 100644 --- a/samples/client/petstore/python/test/test_cat.py +++ b/samples/client/petstore/python/test/test_cat.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.cat import Cat +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.cat import Cat class TestCat(unittest.TestCase): @@ -42,8 +46,8 @@ class TestCat(unittest.TestCase): """ Test Cat """ - model = swagger_client.models.cat.Cat() + model = petstore_api.models.cat.Cat() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_category.py b/samples/client/petstore/python/test/test_category.py index 793fbdf41b0..f4f43796675 100644 --- a/samples/client/petstore/python/test/test_category.py +++ b/samples/client/petstore/python/test/test_category.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.category import Category +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.category import Category class TestCategory(unittest.TestCase): @@ -42,8 +46,8 @@ class TestCategory(unittest.TestCase): """ Test Category """ - model = swagger_client.models.category.Category() + model = petstore_api.models.category.Category() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_dog.py b/samples/client/petstore/python/test/test_dog.py index 044dc5be51f..6bac6d65c30 100644 --- a/samples/client/petstore/python/test/test_dog.py +++ b/samples/client/petstore/python/test/test_dog.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.dog import Dog +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.dog import Dog class TestDog(unittest.TestCase): @@ -42,8 +46,8 @@ class TestDog(unittest.TestCase): """ Test Dog """ - model = swagger_client.models.dog.Dog() + model = petstore_api.models.dog.Dog() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_enum_class.py b/samples/client/petstore/python/test/test_enum_class.py new file mode 100644 index 00000000000..6d9c50255df --- /dev/null +++ b/samples/client/petstore/python/test/test_enum_class.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.enum_class import EnumClass + + +class TestEnumClass(unittest.TestCase): + """ EnumClass unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testEnumClass(self): + """ + Test EnumClass + """ + model = petstore_api.models.enum_class.EnumClass() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_enum_test.py b/samples/client/petstore/python/test/test_enum_test.py new file mode 100644 index 00000000000..aa8d86a6d78 --- /dev/null +++ b/samples/client/petstore/python/test/test_enum_test.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.enum_test import EnumTest + + +class TestEnumTest(unittest.TestCase): + """ EnumTest unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testEnumTest(self): + """ + Test EnumTest + """ + model = petstore_api.models.enum_test.EnumTest() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_fake_api.py b/samples/client/petstore/python/test/test_fake_api.py index 29b71bdf81a..cddf28289ba 100644 --- a/samples/client/petstore/python/test/test_fake_api.py +++ b/samples/client/petstore/python/test/test_fake_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.fake_api import FakeApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.fake_api import FakeApi class TestFakeApi(unittest.TestCase): """ FakeApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.fake_api.FakeApi() + self.api = petstore_api.apis.fake_api.FakeApi() def tearDown(self): pass @@ -42,10 +46,10 @@ class TestFakeApi(unittest.TestCase): """ Test case for test_endpoint_parameters - Fake endpoint for testing various parameters + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 """ pass if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_format_test.py b/samples/client/petstore/python/test/test_format_test.py index 11101ad52da..2c3d0039dce 100644 --- a/samples/client/petstore/python/test/test_format_test.py +++ b/samples/client/petstore/python/test/test_format_test.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.format_test import FormatTest +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.format_test import FormatTest class TestFormatTest(unittest.TestCase): @@ -42,8 +46,8 @@ class TestFormatTest(unittest.TestCase): """ Test FormatTest """ - model = swagger_client.models.format_test.FormatTest() + model = petstore_api.models.format_test.FormatTest() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py new file mode 100644 index 00000000000..90f13e029e2 --- /dev/null +++ b/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass + + +class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): + """ MixedPropertiesAndAdditionalPropertiesClass unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMixedPropertiesAndAdditionalPropertiesClass(self): + """ + Test MixedPropertiesAndAdditionalPropertiesClass + """ + model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_model_200_response.py b/samples/client/petstore/python/test/test_model_200_response.py index 8328d2b9757..0b30fa81c89 100644 --- a/samples/client/petstore/python/test/test_model_200_response.py +++ b/samples/client/petstore/python/test/test_model_200_response.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.model_200_response import Model200Response +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.model_200_response import Model200Response class TestModel200Response(unittest.TestCase): @@ -42,8 +46,8 @@ class TestModel200Response(unittest.TestCase): """ Test Model200Response """ - model = swagger_client.models.model_200_response.Model200Response() + model = petstore_api.models.model_200_response.Model200Response() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_model_return.py b/samples/client/petstore/python/test/test_model_return.py index 4ff3f38b2eb..149d658c7cf 100644 --- a/samples/client/petstore/python/test/test_model_return.py +++ b/samples/client/petstore/python/test/test_model_return.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.model_return import ModelReturn +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.model_return import ModelReturn class TestModelReturn(unittest.TestCase): @@ -42,8 +46,8 @@ class TestModelReturn(unittest.TestCase): """ Test ModelReturn """ - model = swagger_client.models.model_return.ModelReturn() + model = petstore_api.models.model_return.ModelReturn() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_name.py b/samples/client/petstore/python/test/test_name.py index c3b27897eb1..ae3b6106d62 100644 --- a/samples/client/petstore/python/test/test_name.py +++ b/samples/client/petstore/python/test/test_name.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.name import Name +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.name import Name class TestName(unittest.TestCase): @@ -42,8 +46,8 @@ class TestName(unittest.TestCase): """ Test Name """ - model = swagger_client.models.name.Name() + model = petstore_api.models.name.Name() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_order.py b/samples/client/petstore/python/test/test_order.py index 23beefe346c..e2a1290ffc7 100644 --- a/samples/client/petstore/python/test/test_order.py +++ b/samples/client/petstore/python/test/test_order.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.order import Order +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.order import Order class TestOrder(unittest.TestCase): @@ -42,8 +46,8 @@ class TestOrder(unittest.TestCase): """ Test Order """ - model = swagger_client.models.order.Order() + model = petstore_api.models.order.Order() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_pet.py b/samples/client/petstore/python/test/test_pet.py index 471b7b4f67c..9148c0ac119 100644 --- a/samples/client/petstore/python/test/test_pet.py +++ b/samples/client/petstore/python/test/test_pet.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.pet import Pet +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.pet import Pet class TestPet(unittest.TestCase): @@ -42,8 +46,8 @@ class TestPet(unittest.TestCase): """ Test Pet """ - model = swagger_client.models.pet.Pet() + model = petstore_api.models.pet.Pet() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_pet_api.py b/samples/client/petstore/python/test/test_pet_api.py index 81ee6c76e9c..c9ef2d87c45 100644 --- a/samples/client/petstore/python/test/test_pet_api.py +++ b/samples/client/petstore/python/test/test_pet_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.pet_api import PetApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.pet_api import PetApi class TestPetApi(unittest.TestCase): """ PetApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.pet_api.PetApi() + self.api = petstore_api.apis.pet_api.PetApi() def tearDown(self): pass @@ -104,4 +108,4 @@ class TestPetApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_read_only_first.py b/samples/client/petstore/python/test/test_read_only_first.py new file mode 100644 index 00000000000..3579ebefb48 --- /dev/null +++ b/samples/client/petstore/python/test/test_read_only_first.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + 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 + + 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. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.read_only_first import ReadOnlyFirst + + +class TestReadOnlyFirst(unittest.TestCase): + """ ReadOnlyFirst unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testReadOnlyFirst(self): + """ + Test ReadOnlyFirst + """ + model = petstore_api.models.read_only_first.ReadOnlyFirst() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_special_model_name.py b/samples/client/petstore/python/test/test_special_model_name.py index 17c12655031..1991883e3c1 100644 --- a/samples/client/petstore/python/test/test_special_model_name.py +++ b/samples/client/petstore/python/test/test_special_model_name.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.special_model_name import SpecialModelName +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.special_model_name import SpecialModelName class TestSpecialModelName(unittest.TestCase): @@ -42,8 +46,8 @@ class TestSpecialModelName(unittest.TestCase): """ Test SpecialModelName """ - model = swagger_client.models.special_model_name.SpecialModelName() + model = petstore_api.models.special_model_name.SpecialModelName() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_store_api.py b/samples/client/petstore/python/test/test_store_api.py index e8dc0a64b1c..0278685372b 100644 --- a/samples/client/petstore/python/test/test_store_api.py +++ b/samples/client/petstore/python/test/test_store_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.store_api import StoreApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.store_api import StoreApi class TestStoreApi(unittest.TestCase): """ StoreApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.store_api.StoreApi() + self.api = petstore_api.apis.store_api.StoreApi() def tearDown(self): pass @@ -72,4 +76,4 @@ class TestStoreApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_tag.py b/samples/client/petstore/python/test/test_tag.py index 35b51e4d7d2..c86dcbb1d5f 100644 --- a/samples/client/petstore/python/test/test_tag.py +++ b/samples/client/petstore/python/test/test_tag.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.tag import Tag +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.tag import Tag class TestTag(unittest.TestCase): @@ -42,8 +46,8 @@ class TestTag(unittest.TestCase): """ Test Tag """ - model = swagger_client.models.tag.Tag() + model = petstore_api.models.tag.Tag() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_user.py b/samples/client/petstore/python/test/test_user.py index 1aad154cbf8..328c07baa88 100644 --- a/samples/client/petstore/python/test/test_user.py +++ b/samples/client/petstore/python/test/test_user.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.user import User +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.user import User class TestUser(unittest.TestCase): @@ -42,8 +46,8 @@ class TestUser(unittest.TestCase): """ Test User """ - model = swagger_client.models.user.User() + model = petstore_api.models.user.User() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_user_api.py b/samples/client/petstore/python/test/test_user_api.py index 0205fe7383a..032d00af315 100644 --- a/samples/client/petstore/python/test/test_user_api.py +++ b/samples/client/petstore/python/test/test_user_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - 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 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - 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. + 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 - ref: https://github.com/swagger-api/swagger-codegen + 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. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.user_api import UserApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.user_api import UserApi class TestUserApi(unittest.TestCase): """ UserApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.user_api.UserApi() + self.api = petstore_api.apis.user_api.UserApi() def tearDown(self): pass @@ -104,4 +108,4 @@ class TestUserApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/tests/test_api_client.py b/samples/client/petstore/python/tests/test_api_client.py index 61c57cb7e46..972175835f3 100644 --- a/samples/client/petstore/python/tests/test_api_client.py +++ b/samples/client/petstore/python/tests/test_api_client.py @@ -12,8 +12,8 @@ import time import unittest from dateutil.parser import parse -import swagger_client -import swagger_client.configuration +import petstore_api +import petstore_api.configuration HOST = 'http://petstore.swagger.io/v2' @@ -21,20 +21,20 @@ HOST = 'http://petstore.swagger.io/v2' class ApiClientTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient(HOST) + self.api_client = petstore_api.ApiClient(HOST) def test_configuration(self): - swagger_client.configuration.api_key['api_key'] = '123456' - swagger_client.configuration.api_key_prefix['api_key'] = 'PREFIX' - swagger_client.configuration.username = 'test_username' - swagger_client.configuration.password = 'test_password' + petstore_api.configuration.api_key['api_key'] = '123456' + petstore_api.configuration.api_key_prefix['api_key'] = 'PREFIX' + petstore_api.configuration.username = 'test_username' + petstore_api.configuration.password = 'test_password' header_params = {'test1': 'value1'} query_params = {'test2': 'value2'} auth_settings = ['api_key', 'unknown'] # test prefix - self.assertEqual('PREFIX', swagger_client.configuration.api_key_prefix['api_key']) + self.assertEqual('PREFIX', petstore_api.configuration.api_key_prefix['api_key']) # update parameters based on auth setting self.api_client.update_params_for_auth(header_params, query_params, auth_settings) @@ -45,8 +45,8 @@ class ApiClientTests(unittest.TestCase): self.assertEqual(query_params['test2'], 'value2') # test basic auth - self.assertEqual('test_username', swagger_client.configuration.username) - self.assertEqual('test_password', swagger_client.configuration.password) + self.assertEqual('test_username', petstore_api.configuration.username) + self.assertEqual('test_password', petstore_api.configuration.password) def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] @@ -139,17 +139,17 @@ class ApiClientTests(unittest.TestCase): "status": "available", "photoUrls": ["http://foo.bar.com/3", "http://foo.bar.com/4"]} - pet = swagger_client.Pet() + pet = petstore_api.Pet() pet.id = pet_dict["id"] pet.name = pet_dict["name"] - cate = swagger_client.Category() + cate = petstore_api.Category() cate.id = pet_dict["category"]["id"] cate.name = pet_dict["category"]["name"] pet.category = cate - tag1 = swagger_client.Tag() + tag1 = petstore_api.Tag() tag1.id = pet_dict["tags"][0]["id"] tag1.name = pet_dict["tags"][0]["name"] - tag2 = swagger_client.Tag() + tag2 = petstore_api.Tag() tag2.id = pet_dict["tags"][1]["id"] tag2.name = pet_dict["tags"][1]["name"] pet.tags = [tag1, tag2] diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index 790a18dffd0..8df2b681f01 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -12,25 +12,25 @@ import sys import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException class ApiExceptionTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient() - self.pet_api = swagger_client.PetApi(self.api_client) + self.api_client = petstore_api.ApiClient() + self.pet_api = petstore_api.PetApi(self.api_client) self.setUpModels() def setUpModels(self): - self.category = swagger_client.Category() + self.category = petstore_api.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = swagger_client.Tag() + self.tag = petstore_api.Tag() self.tag.id = int(time.time()) self.tag.name = "blank" - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] @@ -44,7 +44,7 @@ class ApiExceptionTests(unittest.TestCase): def test_404_error(self): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id) - + with self.checkRaiseRegex(ApiException, "Pet not found"): self.pet_api.get_pet_by_id(pet_id=self.pet.id) @@ -87,4 +87,3 @@ class ApiExceptionTests(unittest.TestCase): return self.assertRegexpMatches(text, expected_regex) return self.assertRegex(text, expected_regex) - diff --git a/samples/client/petstore/python/tests/test_deserialization.py b/samples/client/petstore/python/tests/test_deserialization.py index 1eae045ff76..143f22b64bd 100644 --- a/samples/client/petstore/python/tests/test_deserialization.py +++ b/samples/client/petstore/python/tests/test_deserialization.py @@ -11,13 +11,13 @@ import time import unittest import datetime -import swagger_client +import petstore_api class DeserializationTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient() + self.api_client = petstore_api.ApiClient() self.deserialize = self.api_client._ApiClient__deserialize def test_deserialize_dict_str_pet(self): @@ -45,7 +45,7 @@ class DeserializationTests(unittest.TestCase): deserialized = self.deserialize(data, 'dict(str, Pet)') self.assertTrue(isinstance(deserialized, dict)) - self.assertTrue(isinstance(deserialized['pet'], swagger_client.Pet)) + self.assertTrue(isinstance(deserialized['pet'], petstore_api.Pet)) def test_deserialize_dict_str_int(self): """ deserialize dict(str, int) """ @@ -78,12 +78,42 @@ class DeserializationTests(unittest.TestCase): def test_deserialize_pet(self): """ deserialize pet """ data = { + "id": 0, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "name": "string" + } + ], + "status": "available" + } + deserialized = self.deserialize(data, "Pet") + self.assertTrue(isinstance(deserialized, petstore_api.Pet)) + self.assertEqual(deserialized.id, 0) + self.assertEqual(deserialized.name, "doggie") + self.assertTrue(isinstance(deserialized.category, petstore_api.Category)) + self.assertEqual(deserialized.category.name, "string") + self.assertTrue(isinstance(deserialized.tags, list)) + self.assertEqual(deserialized.tags[0].name, "string") + + def test_deserialize_list_of_pet(self): + """ deserialize list[Pet] """ + data = [ + { "id": 0, "category": { "id": 0, "name": "string" }, - "name": "doggie", + "name": "doggie0", "photoUrls": [ "string" ], @@ -94,57 +124,28 @@ class DeserializationTests(unittest.TestCase): } ], "status": "available" - } - deserialized = self.deserialize(data, "Pet") - self.assertTrue(isinstance(deserialized, swagger_client.Pet)) - self.assertEqual(deserialized.id, 0) - self.assertEqual(deserialized.name, "doggie") - self.assertTrue(isinstance(deserialized.category, swagger_client.Category)) - self.assertEqual(deserialized.category.name, "string") - self.assertTrue(isinstance(deserialized.tags, list)) - self.assertEqual(deserialized.tags[0].name, "string") - - def test_deserialize_list_of_pet(self): - """ deserialize list[Pet] """ - data = [{ - "id": 0, - "category": { - "id": 0, - "name": "string" }, - "name": "doggie0", - "photoUrls": [ - "string" - ], - "tags": [ - { + { + "id": 1, + "category": { "id": 0, "name": "string" - } - ], - "status": "available" - }, - { - "id": 1, - "category": { - "id": 0, - "name": "string" - }, - "name": "doggie1", - "photoUrls": [ - "string" - ], - "tags": [ - { - "id": 0, - "name": "string" - } - ], - "status": "available" - }] + }, + "name": "doggie1", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "name": "string" + } + ], + "status": "available" + }] deserialized = self.deserialize(data, "list[Pet]") self.assertTrue(isinstance(deserialized, list)) - self.assertTrue(isinstance(deserialized[0], swagger_client.Pet)) + self.assertTrue(isinstance(deserialized[0], petstore_api.Pet)) self.assertEqual(deserialized[0].id, 0) self.assertEqual(deserialized[1].id, 1) self.assertEqual(deserialized[0].name, "doggie0") diff --git a/samples/client/petstore/python/tests/test_order_model.py b/samples/client/petstore/python/tests/test_order_model.py index e411ca0103d..710f3c175a9 100644 --- a/samples/client/petstore/python/tests/test_order_model.py +++ b/samples/client/petstore/python/tests/test_order_model.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,13 +11,13 @@ import os import time import unittest -import swagger_client +import petstore_api class OrderModelTests(unittest.TestCase): def test_status(self): - order = swagger_client.Order() + order = petstore_api.Order() order.status = "placed" self.assertEqual("placed", order.status) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 300a7bee783..4b749fc044a 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,8 +11,8 @@ import os import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException HOST = 'http://petstore.swagger.io/v2' @@ -20,8 +20,8 @@ HOST = 'http://petstore.swagger.io/v2' class PetApiTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient(HOST) - self.pet_api = swagger_client.PetApi(self.api_client) + self.api_client = petstore_api.ApiClient(HOST) + self.pet_api = petstore_api.PetApi(self.api_client) self.setUpModels() self.setUpFiles() @@ -30,13 +30,13 @@ class PetApiTests(unittest.TestCase): time.sleep(1) def setUpModels(self): - self.category = swagger_client.Category() + self.category = petstore_api.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = swagger_client.Tag() + self.tag = petstore_api.Tag() self.tag.id = int(time.time()) self.tag.name = "swagger-codegen-python-pet-tag" - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] @@ -50,22 +50,22 @@ class PetApiTests(unittest.TestCase): self.foo = os.path.join(self.test_file_dir, "foo.png") def test_create_api_instance(self): - pet_api = swagger_client.PetApi() - pet_api2 = swagger_client.PetApi() - api_client3 = swagger_client.ApiClient() + pet_api = petstore_api.PetApi() + pet_api2 = petstore_api.PetApi() + api_client3 = petstore_api.ApiClient() api_client3.user_agent = 'api client 3' - api_client4 = swagger_client.ApiClient() + api_client4 = petstore_api.ApiClient() api_client4.user_agent = 'api client 4' - pet_api3 = swagger_client.PetApi(api_client3) + pet_api3 = petstore_api.PetApi(api_client3) # same default api client self.assertEqual(pet_api.api_client, pet_api2.api_client) # confirm using the default api client in the config module - self.assertEqual(pet_api.api_client, swagger_client.configuration.api_client) + self.assertEqual(pet_api.api_client, petstore_api.configuration.api_client) # 2 different api clients are not the same self.assertNotEqual(api_client3, api_client4) # customized pet api not using the default api client - self.assertNotEqual(pet_api3.api_client, swagger_client.configuration.api_client) + self.assertNotEqual(pet_api3.api_client, petstore_api.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) diff --git a/samples/client/petstore/python/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py index d2bd3c9ca3d..52cb55061da 100644 --- a/samples/client/petstore/python/tests/test_pet_model.py +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,22 +11,22 @@ import os import time import unittest -import swagger_client +import petstore_api class PetModelTests(unittest.TestCase): def setUp(self): - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.name = "test name" self.pet.id = 1 self.pet.photo_urls = ["string"] self.pet.status = "available" - cate = swagger_client.Category() + cate = petstore_api.Category() cate.id = 1 cate.name = "dog" self.pet.category = cate - tag = swagger_client.Tag() + tag = petstore_api.Tag() tag.id = 1 self.pet.tags = [tag] @@ -40,29 +40,29 @@ class PetModelTests(unittest.TestCase): self.assertEqual(data, self.pet.to_str()) def test_equal(self): - self.pet1 = swagger_client.Pet() + self.pet1 = petstore_api.Pet() self.pet1.name = "test name" self.pet1.id = 1 self.pet1.photo_urls = ["string"] self.pet1.status = "available" - cate1 = swagger_client.Category() + cate1 = petstore_api.Category() cate1.id = 1 cate1.name = "dog" self.pet.category = cate1 - tag1 = swagger_client.Tag() + tag1 = petstore_api.Tag() tag1.id = 1 self.pet1.tags = [tag1] - self.pet2 = swagger_client.Pet() + self.pet2 = petstore_api.Pet() self.pet2.name = "test name" self.pet2.id = 1 self.pet2.photo_urls = ["string"] self.pet2.status = "available" - cate2 = swagger_client.Category() + cate2 = petstore_api.Category() cate2.id = 1 cate2.name = "dog" self.pet.category = cate2 - tag2 = swagger_client.Tag() + tag2 = petstore_api.Tag() tag2.id = 1 self.pet2.tags = [tag2] diff --git a/samples/client/petstore/python/tests/test_store_api.py b/samples/client/petstore/python/tests/test_store_api.py index 42b92d0879c..b7e80281707 100644 --- a/samples/client/petstore/python/tests/test_store_api.py +++ b/samples/client/petstore/python/tests/test_store_api.py @@ -11,14 +11,14 @@ import os import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException class StoreApiTests(unittest.TestCase): def setUp(self): - self.store_api = swagger_client.StoreApi() + self.store_api = petstore_api.StoreApi() def tearDown(self): # sleep 1 sec between two every 2 tests diff --git a/samples/client/petstore/python/tox.ini b/samples/client/petstore/python/tox.ini index 9f62f3845bf..d99517b76b6 100644 --- a/samples/client/petstore/python/tox.ini +++ b/samples/client/petstore/python/tox.ini @@ -2,9 +2,9 @@ envlist = py27, py34 [testenv] -deps= -r{toxinidir}/dev-requirements.txt +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + commands= nosetests \ - [] -setenv = - PYTHONWARNINGS=always::DeprecationWarning + [] \ No newline at end of file diff --git a/samples/client/petstore/ruby/.gitignore b/samples/client/petstore/ruby/.gitignore index a8b1cda23f8..522134fcdd3 100644 --- a/samples/client/petstore/ruby/.gitignore +++ b/samples/client/petstore/ruby/.gitignore @@ -1,3 +1,17 @@ +# 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. + *.gem *.rbc /.config diff --git a/samples/client/petstore/ruby/.swagger-codegen-ignore b/samples/client/petstore/ruby/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/ruby/.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 +# Thsi 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/ruby/LICENSE b/samples/client/petstore/ruby/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/ruby/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 7aa7d19b003..6038fb2cbc1 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-11T16:13:11.464+08:00 +- Build date: 2016-05-25T01:17:54.676+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -116,20 +116,24 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [Petstore::AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Petstore::Animal](docs/Animal.md) - [Petstore::AnimalFarm](docs/AnimalFarm.md) - [Petstore::ApiResponse](docs/ApiResponse.md) + - [Petstore::ArrayTest](docs/ArrayTest.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::Dog](docs/Dog.md) - [Petstore::EnumClass](docs/EnumClass.md) - [Petstore::EnumTest](docs/EnumTest.md) - [Petstore::FormatTest](docs/FormatTest.md) + - [Petstore::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Petstore::Model200Response](docs/Model200Response.md) - [Petstore::ModelReturn](docs/ModelReturn.md) - [Petstore::Name](docs/Name.md) - [Petstore::Order](docs/Order.md) - [Petstore::Pet](docs/Pet.md) + - [Petstore::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Petstore::SpecialModelName](docs/SpecialModelName.md) - [Petstore::Tag](docs/Tag.md) - [Petstore::User](docs/User.md) diff --git a/samples/client/petstore/ruby/docs/AdditionalPropertiesClass.md b/samples/client/petstore/ruby/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..8c9c63a74a3 --- /dev/null +++ b/samples/client/petstore/ruby/docs/AdditionalPropertiesClass.md @@ -0,0 +1,7 @@ +# Petstore::AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/ArrayTest.md b/samples/client/petstore/ruby/docs/ArrayTest.md new file mode 100644 index 00000000000..aa084814f0f --- /dev/null +++ b/samples/client/petstore/ruby/docs/ArrayTest.md @@ -0,0 +1,7 @@ +# Petstore::ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index c0312e00f51..7b687dc67b9 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -75,8 +75,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/ruby/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/ruby/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..973c03c8396 --- /dev/null +++ b/samples/client/petstore/ruby/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,9 @@ +# Petstore::MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**date_time** | **DateTime** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/PetApi.md b/samples/client/petstore/ruby/docs/PetApi.md index d5a498c6ff0..1acc4382aa3 100644 --- a/samples/client/petstore/ruby/docs/PetApi.md +++ b/samples/client/petstore/ruby/docs/PetApi.md @@ -25,7 +25,7 @@ Add a new pet to the store ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -76,7 +76,7 @@ Deletes a pet ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -131,7 +131,7 @@ Multiple status values can be provided with comma separated strings ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -183,7 +183,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -235,7 +235,7 @@ Returns a single pet ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure API key authorization: api_key config.api_key['api_key'] = 'YOUR API KEY' @@ -289,7 +289,7 @@ Update an existing pet ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -340,7 +340,7 @@ Updates a pet in the store with form data ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' @@ -397,7 +397,7 @@ uploads an image ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure OAuth2 access token for authorization: petstore_auth config.access_token = 'YOUR ACCESS TOKEN' diff --git a/samples/client/petstore/ruby/docs/ReadOnlyFirst.md b/samples/client/petstore/ruby/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..e49b5119478 --- /dev/null +++ b/samples/client/petstore/ruby/docs/ReadOnlyFirst.md @@ -0,0 +1,9 @@ +# Petstore::ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/StoreApi.md b/samples/client/petstore/ruby/docs/StoreApi.md index c38a41eeef4..a58e25c1c2f 100644 --- a/samples/client/petstore/ruby/docs/StoreApi.md +++ b/samples/client/petstore/ruby/docs/StoreApi.md @@ -67,7 +67,7 @@ Returns a map of status codes to quantities ```ruby # load the gem require 'petstore' -# setup authorization +# setup authorization Petstore.configure do |config| # Configure API key authorization: api_key config.api_key['api_key'] = 'YOUR API KEY' diff --git a/samples/client/petstore/ruby/git_push.sh b/samples/client/petstore/ruby/git_push.sh index ed374619b13..7e44b9aade1 100644 --- a/samples/client/petstore/ruby/git_push.sh +++ b/samples/client/petstore/ruby/git_push.sh @@ -1,4 +1,19 @@ #!/bin/sh +# +# 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. +# # 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" @@ -28,7 +43,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/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index ce77b3d21b6..b8daaf4cb76 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -21,20 +28,24 @@ require 'petstore/version' require 'petstore/configuration' # Models +require 'petstore/models/additional_properties_class' require 'petstore/models/animal' require 'petstore/models/animal_farm' require 'petstore/models/api_response' +require 'petstore/models/array_test' require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/dog' require 'petstore/models/enum_class' require 'petstore/models/enum_test' require 'petstore/models/format_test' +require 'petstore/models/mixed_properties_and_additional_properties_class' require 'petstore/models/model_200_response' require 'petstore/models/model_return' require 'petstore/models/name' require 'petstore/models/order' require 'petstore/models/pet' +require 'petstore/models/read_only_first' require 'petstore/models/special_model_name' require 'petstore/models/tag' require 'petstore/models/user' 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 e7e6e45c262..80f71d81b1a 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -131,11 +138,11 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] + local_header_accept = ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - local_header_content_type = [] + local_header_content_type = ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters 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 2d7a12dfd2a..88dbcdfb662 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end 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 2ef8b526c69..bf4ab2ec8db 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end 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 bdecfa87ec2..3db9234ef90 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 1723abbac42..2ecbea204f9 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index 95b1fc6cdb7..cf271ae8265 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 05973753287..92aeb4010eb 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -1,3 +1,26 @@ +=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 + +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. + +=end + require 'uri' module Petstore diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb new file mode 100644 index 00000000000..6426f058398 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -0,0 +1,188 @@ +=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 + +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. + +=end + +require 'date' + +module Petstore + + class AdditionalPropertiesClass + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + 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} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return 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? + 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 + 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 + [].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 =~ /^Array<(.*)>/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 =~ /^(true|t|yes|y|1)$/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/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index d23fe94a733..a47ea8d19de 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -7,21 +7,30 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Animal attr_accessor :class_name attr_accessor :color + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -68,14 +77,12 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @class_name.nil? - return false - end - + return false if @class_name.nil? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -84,7 +91,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -183,7 +190,7 @@ module Petstore # 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 + # @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) @@ -200,4 +207,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb index f4f2f6ba6a0..8daae9c91c1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -7,17 +7,26 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class AnimalFarm + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -50,17 +59,18 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -159,7 +169,7 @@ module Petstore # 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 + # @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) @@ -176,4 +186,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index 3893b842879..25ad09ca813 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class ApiResponse attr_accessor :code @@ -24,6 +32,7 @@ module Petstore attr_accessor :message + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -74,10 +83,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -87,7 +97,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -186,7 +196,7 @@ module Petstore # 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 + # @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) @@ -203,4 +213,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb new file mode 100644 index 00000000000..35d498fc9af --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -0,0 +1,188 @@ +=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 + +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. + +=end + +require 'date' + +module Petstore + + class ArrayTest + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + 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} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return 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? + 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 + 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 + [].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 =~ /^Array<(.*)>/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 =~ /^(true|t|yes|y|1)$/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/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 653b9b506f7..e4ca7f92fc0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Cat attr_accessor :class_name @@ -24,6 +32,7 @@ module Petstore attr_accessor :declawed + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -76,14 +85,12 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @class_name.nil? - return false - end - + return false if @class_name.nil? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -93,7 +100,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -192,7 +199,7 @@ module Petstore # 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 + # @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) @@ -209,4 +216,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 5aced3c55c7..e7c09fcc514 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -7,21 +7,30 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Category attr_accessor :id attr_accessor :name + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -66,10 +75,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -78,7 +88,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -177,7 +187,7 @@ module Petstore # 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 + # @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) @@ -194,4 +204,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index b08d82d49f8..ed335a91429 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Dog attr_accessor :class_name @@ -24,6 +32,7 @@ module Petstore attr_accessor :breed + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -76,14 +85,12 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @class_name.nil? - return false - end - + return false if @class_name.nil? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -93,7 +100,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -192,7 +199,7 @@ module Petstore # 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 + # @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) @@ -209,4 +216,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb index 30c570708c3..b5046df8f31 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -18,167 +25,10 @@ require 'date' module Petstore class EnumClass - # Attribute mapping from ruby-style variable name to JSON key. - def self.attribute_map - { - } - end - - # Attribute type mapping. - def self.swagger_types - { - } - 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} - - end - - # Show invalid properties with the reasons. Usually used together with valid? - # @return Array for valid properies with the reasons - def list_invalid_properties - invalid_properties = Array.new - allowed_values = ["_abc", "-efg", "(xyz)"] - if @EnumClass && !allowed_values.include?(EnumClass) - invalid_properties.push("invalid value for 'EnumClass', must be one of #{allowed_values}.") - end - - return 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? - 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 - 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 - [].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 =~ /^Array<(.*)>/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 =~ /^(true|t|yes|y|1)$/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 - + + ABC = "_abc".freeze + EFG = "-efg".freeze + XYZ = "(xyz)".freeze 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 618c6336d58..8f1c4c8bec0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class EnumTest attr_accessor :enum_string @@ -24,6 +32,28 @@ module Petstore attr_accessor :enum_number + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -74,26 +104,21 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - allowed_values = ["UPPER", "lower"] - if @enum_string && !allowed_values.include?(@enum_string) - return false - end - allowed_values = ["1", "-1"] - if @enum_integer && !allowed_values.include?(@enum_integer) - return false - end - allowed_values = ["1.1", "-1.2"] - if @enum_number && !allowed_values.include?(@enum_number) - return false - end + enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + return false unless enum_string_validator.valid?(@enum_string) + 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"]) + return false unless enum_number_validator.valid?(@enum_number) + return true end # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_string Object to be assigned def enum_string=(enum_string) - allowed_values = ["UPPER", "lower"] - if enum_string && !allowed_values.include?(enum_string) - fail ArgumentError, "invalid value for 'enum_string', must be one of #{allowed_values}." + validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + unless validator.valid?(enum_string) + fail ArgumentError, "invalid value for 'enum_string', must be one of #{validator.allowable_values}." end @enum_string = enum_string end @@ -101,9 +126,9 @@ module Petstore # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_integer Object to be assigned def enum_integer=(enum_integer) - allowed_values = ["1", "-1"] - if enum_integer && !allowed_values.include?(enum_integer) - fail ArgumentError, "invalid value for 'enum_integer', must be one of #{allowed_values}." + validator = EnumAttributeValidator.new('Integer', ["1", "-1"]) + unless validator.valid?(enum_integer) + fail ArgumentError, "invalid value for 'enum_integer', must be one of #{validator.allowable_values}." end @enum_integer = enum_integer end @@ -111,15 +136,15 @@ module Petstore # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_number Object to be assigned def enum_number=(enum_number) - allowed_values = ["1.1", "-1.2"] - if enum_number && !allowed_values.include?(enum_number) - fail ArgumentError, "invalid value for 'enum_number', must be one of #{allowed_values}." + validator = EnumAttributeValidator.new('Float', ["1.1", "-1.2"]) + unless validator.valid?(enum_number) + fail ArgumentError, "invalid value for 'enum_number', must be one of #{validator.allowable_values}." end @enum_number = enum_number end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -129,7 +154,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -228,7 +253,7 @@ module Petstore # 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 + # @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) @@ -245,4 +270,5 @@ module Petstore end end + end 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 9952352f9fd..668dab29fd7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class FormatTest attr_accessor :integer @@ -44,6 +52,7 @@ module Petstore attr_accessor :password + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -154,74 +163,24 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @integer > 100.0 - return false - end - - if @integer < 10.0 - return false - end - - if @int32 > 200.0 - return false - end - - if @int32 < 20.0 - return false - end - - if @number.nil? - return false - end - - if @number > 543.2 - return false - end - - if @number < 32.1 - return false - end - - if @float > 987.6 - return false - end - - if @float < 54.3 - return false - end - - if @double > 123.4 - return false - end - - if @double < 67.8 - return false - end - - if @string !~ Regexp.new(/[a-z]/i) - return false - end - - if @byte.nil? - return false - end - - if @date.nil? - return false - end - - if @password.nil? - return false - end - - if @password.to_s.length > 64 - return false - end - - if @password.to_s.length < 10 - return false - end - + return false if @integer > 100.0 + return false if @integer < 10.0 + return false if @int32 > 200.0 + return false if @int32 < 20.0 + return false if @number.nil? + return false if @number > 543.2 + return false if @number < 32.1 + return false if @float > 987.6 + return false if @float < 54.3 + return false if @double > 123.4 + return false if @double < 67.8 + return false if @string !~ Regexp.new(/[a-z]/i) + return false if @byte.nil? + return false if @date.nil? + return false if @password.nil? + return false if @password.to_s.length > 64 + return false if @password.to_s.length < 10 + return true end # Custom attribute writer method with validation @@ -347,7 +306,7 @@ module Petstore end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -367,7 +326,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -466,7 +425,7 @@ module Petstore # 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 + # @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) @@ -483,4 +442,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb new file mode 100644 index 00000000000..8208fc64638 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -0,0 +1,206 @@ +=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 + +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. + +=end + +require 'date' + +module Petstore + + class MixedPropertiesAndAdditionalPropertiesClass + attr_accessor :uuid + + attr_accessor :date_time + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'uuid' => :'uuid', + :'date_time' => :'dateTime' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'uuid' => :'String', + :'date_time' => :'DateTime' + } + 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?(:'uuid') + self.uuid = attributes[:'uuid'] + end + + if attributes.has_key?(:'dateTime') + self.date_time = attributes[:'dateTime'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return 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? + 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 && + uuid == o.uuid && + date_time == o.date_time + 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 + [uuid, date_time].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 =~ /^Array<(.*)>/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 =~ /^(true|t|yes|y|1)$/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/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index c7bcf594aca..5e293ef4c61 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -21,6 +28,7 @@ module Petstore class Model200Response attr_accessor :name + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -59,10 +67,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -70,7 +79,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -169,7 +178,7 @@ module Petstore # 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 + # @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) @@ -186,4 +195,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 1a18970eebe..7bda1eea5e6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -21,6 +28,7 @@ module Petstore class ModelReturn attr_accessor :_return + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -59,10 +67,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -70,7 +79,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -169,7 +178,7 @@ module Petstore # 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 + # @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) @@ -186,4 +195,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 0b4d3835d0e..94247c1ed2f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end @@ -27,6 +34,7 @@ module Petstore attr_accessor :_123_number + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -83,14 +91,12 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @name.nil? - return false - end - + return false if @name.nil? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -101,7 +107,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -200,7 +206,7 @@ module Petstore # 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 + # @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) @@ -217,4 +223,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index e0397710618..87931c88d1d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Order attr_accessor :id @@ -31,6 +39,28 @@ module Petstore attr_accessor :complete + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -101,24 +131,23 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - allowed_values = ["placed", "approved", "delivered"] - if @status && !allowed_values.include?(@status) - return false - end + status_validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + return false unless status_validator.valid?(@status) + return true end # Custom attribute writer method checking allowed values (enum). # @param [Object] status Object to be assigned def status=(status) - allowed_values = ["placed", "approved", "delivered"] - if status && !allowed_values.include?(status) - fail ArgumentError, "invalid value for 'status', must be one of #{allowed_values}." + validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for 'status', must be one of #{validator.allowable_values}." end @status = status end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -131,7 +160,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -230,7 +259,7 @@ module Petstore # 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 + # @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) @@ -247,4 +276,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 0f484cd0c43..f499ba759db 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Pet attr_accessor :id @@ -31,6 +39,28 @@ module Petstore # pet status in the store attr_accessor :status + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -103,32 +133,25 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - if @name.nil? - return false - end - - if @photo_urls.nil? - return false - end - - allowed_values = ["available", "pending", "sold"] - if @status && !allowed_values.include?(@status) - return false - end + return false if @name.nil? + return false if @photo_urls.nil? + status_validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + return false unless status_validator.valid?(@status) + return true end # Custom attribute writer method checking allowed values (enum). # @param [Object] status Object to be assigned def status=(status) - allowed_values = ["available", "pending", "sold"] - if status && !allowed_values.include?(status) - fail ArgumentError, "invalid value for 'status', must be one of #{allowed_values}." + validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for 'status', must be one of #{validator.allowable_values}." end @status = status end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -141,7 +164,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -240,7 +263,7 @@ module Petstore # 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 + # @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) @@ -257,4 +280,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb new file mode 100644 index 00000000000..4f8b79f225e --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -0,0 +1,206 @@ +=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 + +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. + +=end + +require 'date' + +module Petstore + + class ReadOnlyFirst + attr_accessor :bar + + attr_accessor :baz + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'bar' => :'bar', + :'baz' => :'baz' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'bar' => :'String', + :'baz' => :'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?(:'bar') + self.bar = attributes[:'bar'] + end + + if attributes.has_key?(:'baz') + self.baz = attributes[:'baz'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return 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? + 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 && + bar == o.bar && + baz == o.baz + 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 + [bar, baz].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 =~ /^Array<(.*)>/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 =~ /^(true|t|yes|y|1)$/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/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 781cf39ad0c..8726b4bb23f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -7,19 +7,28 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class SpecialModelName attr_accessor :special_property_name + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -58,10 +67,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -69,7 +79,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -168,7 +178,7 @@ module Petstore # 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 + # @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) @@ -185,4 +195,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index b40ad1046f1..72583dfb24c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -7,21 +7,30 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class Tag attr_accessor :id attr_accessor :name + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -66,10 +75,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -78,7 +88,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -177,7 +187,7 @@ module Petstore # 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 + # @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) @@ -194,4 +204,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 8bdc816bd0e..d92a6dfdf13 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -7,16 +7,24 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end require 'date' module Petstore + class User attr_accessor :id @@ -35,6 +43,7 @@ module Petstore # User Status attr_accessor :user_status + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -115,10 +124,11 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. - # @param [Object] Object to be compared + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -133,7 +143,7 @@ module Petstore end # @see the `==` method - # @param [Object] Object to be compared + # @param [Object] Object to be compared def eql?(o) self == o end @@ -232,7 +242,7 @@ module Petstore # 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 + # @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) @@ -249,4 +259,5 @@ module Petstore end end + end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb index e5c868d3d09..58d992d9c27 100644 --- a/samples/client/petstore/ruby/lib/petstore/version.rb +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -7,10 +7,17 @@ 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 +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 -Terms of Service: http://swagger.io/terms/ +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. =end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 66258d1ff5c..f52a27ba00f 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -1,4 +1,28 @@ # -*- encoding: utf-8 -*- +# +=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 + +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. + +=end + $:.push File.expand_path("../lib", __FILE__) require "petstore/version" diff --git a/samples/client/petstore/ruby/spec/.spec_helper.rb b/samples/client/petstore/ruby/spec/.spec_helper.rb new file mode 100644 index 00000000000..50702c439b7 --- /dev/null +++ b/samples/client/petstore/ruby/spec/.spec_helper.rb @@ -0,0 +1,71 @@ +require 'rubygems' +require 'bundler/setup' +require 'petstore' +require 'vcr' +require 'typhoeus' +require 'json' +require 'yaml' +require 'rspec' + +RSpec.configure do |config| + # some (optional) config here + config.expect_with :rspec do |c| + c.syntax = :should + end + config.mock_with :rspec do |c| + c.syntax = :should + end +end + + +WebMock.allow_net_connect! if defined? WebMock + +def help + puts "\nOh noes! You gotta stuff your swagger credentials in ~/.swagger.yml like so:\n\n" + puts "api_key: '12345abcdefg'" + puts "username: 'fumanchu'" + puts "password: 'kalamazoo'\n\n" + exit +end + +# no longer reading credentials (not used) from file (20150413) +# Parse ~/.swagger.yml for user credentials +#begin +# CREDENTIALS = YAML::load_file(File.join(ENV['HOME'], ".swagger.yml")).symbolize_keys +#rescue +# help +#end + +API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) + +def random_id + rand(1000000) + 20000 +end + +# create a random pet, return its id +def prepare_pet(pet_api) + pet_id = random_id + category = Petstore::Category.new('id' => 20002, 'name' => 'category test') + tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test') + pet = Petstore::Pet.new('id' => pet_id, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', + 'category' => category, 'tags' => [tag], 'status' => 'pending') + pet_api.add_pet(pet) + return pet_id +end + +# create a random order, return its id +def prepare_store(store_api) + order_id = 5 + order = Petstore::Order.new("id" => order_id, + "petId" => 123, + "quantity" => 789, + "shipDate" => "2015-04-06T23:42:01.678Z", + "status" => "placed", + "complete" => false) + store_api.place_order(order) + return order_id +end + +# A random string to tack onto stuff to ensure we're not seeing +# data from a previous test run +RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index 3e57a432391..15468683bc3 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -10,34 +10,34 @@ describe Petstore::ApiClient do context 'host' do it 'removes http from host' do Petstore.configure { |c| c.host = 'http://example.com' } - Petstore::Configuration.default.host.should == 'example.com' + expect(Petstore::Configuration.default.host).to eq('example.com') end it 'removes https from host' do Petstore.configure { |c| c.host = 'https://wookiee.com' } - Petstore::ApiClient.default.config.host.should == 'wookiee.com' + expect(Petstore::ApiClient.default.config.host).to eq('wookiee.com') end it 'removes trailing path from host' do Petstore.configure { |c| c.host = 'hobo.com/v4' } - Petstore::Configuration.default.host.should == 'hobo.com' + expect(Petstore::Configuration.default.host).to eq('hobo.com') end end context 'base_path' do it "prepends a slash to base_path" do Petstore.configure { |c| c.base_path = 'v4/dog' } - Petstore::Configuration.default.base_path.should == '/v4/dog' + expect(Petstore::Configuration.default.base_path).to eq('/v4/dog') end it "doesn't prepend a slash if one is already there" do Petstore.configure { |c| c.base_path = '/v4/dog' } - Petstore::Configuration.default.base_path.should == '/v4/dog' + expect(Petstore::Configuration.default.base_path).to eq('/v4/dog') end it "ends up as a blank string if nil" do Petstore.configure { |c| c.base_path = nil } - Petstore::Configuration.default.base_path.should == '' + expect(Petstore::Configuration.default.base_path).to eq('') end end @@ -65,14 +65,14 @@ describe Petstore::ApiClient do header_params = {} query_params = {} api_client.update_params_for_auth! header_params, query_params, auth_names - header_params.should == {'api_key' => 'PREFIX special-key'} - query_params.should == {} + expect(header_params).to eq({'api_key' => 'PREFIX special-key'}) + expect(query_params).to eq({}) header_params = {} query_params = {} api_client2.update_params_for_auth! header_params, query_params, auth_names - header_params.should == {'api_key' => 'PREFIX2 special-key2'} - query_params.should == {} + expect(header_params).to eq({'api_key' => 'PREFIX2 special-key2'}) + expect(query_params).to eq({}) end it "sets header api-key parameter without prefix" do @@ -87,8 +87,8 @@ describe Petstore::ApiClient do query_params = {} auth_names = ['api_key', 'unknown'] api_client.update_params_for_auth! header_params, query_params, auth_names - header_params.should == {'api_key' => 'special-key'} - query_params.should == {} + expect(header_params).to eq({'api_key' => 'special-key'}) + expect(query_params).to eq({}) end end @@ -97,17 +97,17 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new(config) } it "defaults to 0" do - Petstore::Configuration.default.timeout.should == 0 - config.timeout.should == 0 + expect(Petstore::Configuration.default.timeout).to eq(0) + expect(config.timeout).to eq(0) request = api_client.build_request(:get, '/test') - request.options[:timeout].should == 0 + expect(request.options[:timeout]).to eq(0) end it "can be customized" do config.timeout = 100 request = api_client.build_request(:get, '/test') - request.options[:timeout].should == 100 + expect(request.options[:timeout]).to eq(100) end end @@ -117,8 +117,8 @@ describe Petstore::ApiClient do headers = {'Content-Type' => 'application/json'} response = double('response', headers: headers, body: '[12, 34]') data = api_client.deserialize(response, 'Array') - data.should be_a(Array) - data.should == [12, 34] + expect(data).to be_a(Array) + expect(data).to eq([12, 34]) end it "handles Array>" do @@ -126,8 +126,8 @@ describe Petstore::ApiClient do headers = {'Content-Type' => 'application/json'} response = double('response', headers: headers, body: '[[12, 34], [56]]') data = api_client.deserialize(response, 'Array>') - data.should be_a(Array) - data.should == [[12, 34], [56]] + expect(data).to be_a(Array) + expect(data).to eq([[12, 34], [56]]) end it "handles Hash" do @@ -135,8 +135,8 @@ describe Petstore::ApiClient do headers = {'Content-Type' => 'application/json'} response = double('response', headers: headers, body: '{"message": "Hello"}') data = api_client.deserialize(response, 'Hash') - data.should be_a(Hash) - data.should == {:message => 'Hello'} + expect(data).to be_a(Hash) + expect(data).to eq({:message => 'Hello'}) end it "handles Hash" do @@ -144,11 +144,11 @@ describe Petstore::ApiClient do headers = {'Content-Type' => 'application/json'} response = double('response', headers: headers, body: '{"pet": {"id": 1}}') data = api_client.deserialize(response, 'Hash') - data.should be_a(Hash) - data.keys.should == [:pet] + expect(data).to be_a(Hash) + expect(data.keys).to eq([:pet]) pet = data[:pet] - pet.should be_a(Petstore::Pet) - pet.id.should == 1 + expect(pet).to be_a(Petstore::Pet) + expect(pet.id).to eq(1) end it "handles Hash>" do @@ -156,14 +156,14 @@ describe Petstore::ApiClient do headers = {'Content-Type' => 'application/json'} response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}') result = api_client.deserialize(response, 'Hash>') - result.should be_a(Hash) - result.keys.should == [:data] + expect(result).to be_a(Hash) + expect(result.keys).to eq([:data]) data = result[:data] - data.should be_a(Hash) - data.keys.should == [:pet] + expect(data).to be_a(Hash) + expect(data.keys).to eq([:pet]) pet = data[:pet] - pet.should be_a(Petstore::Pet) - pet.id.should == 1 + expect(pet).to be_a(Petstore::Pet) + expect(pet.id).to eq(1) end end @@ -177,7 +177,7 @@ describe Petstore::ApiClient do pet.photo_urls = nil pet.tags = [] expected = {id: 1, name: '', tags: []} - api_client.object_to_hash(pet).should == expected + expect(api_client.object_to_hash(pet)).to eq(expected) end end @@ -186,27 +186,27 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new } it "works for csv" do - api_client.build_collection_param(param, :csv).should == 'aa,bb,cc' + expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') end it "works for ssv" do - api_client.build_collection_param(param, :ssv).should == 'aa bb cc' + expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') end it "works for tsv" do - api_client.build_collection_param(param, :tsv).should == "aa\tbb\tcc" + expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") end it "works for pipes" do - api_client.build_collection_param(param, :pipes).should == 'aa|bb|cc' + expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') end it "works for multi" do - api_client.build_collection_param(param, :multi).should == ['aa', 'bb', 'cc'] + expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) end it "fails for invalid collection format" do - proc { api_client.build_collection_param(param, :INVALID) }.should raise_error(RuntimeError, 'unknown collection format: :INVALID') + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') end end @@ -214,16 +214,16 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new } it "works" do - api_client.json_mime?(nil).should == false - api_client.json_mime?('').should == false + expect(api_client.json_mime?(nil)).to eq(false) + expect(api_client.json_mime?('')).to eq(false) - api_client.json_mime?('application/json').should == true - api_client.json_mime?('application/json; charset=UTF8').should == true - api_client.json_mime?('APPLICATION/JSON').should == true + expect(api_client.json_mime?('application/json')).to eq(true) + expect(api_client.json_mime?('application/json; charset=UTF8')).to eq(true) + expect(api_client.json_mime?('APPLICATION/JSON')).to eq(true) - api_client.json_mime?('application/xml').should == false - api_client.json_mime?('text/plain').should == false - api_client.json_mime?('application/jsonp').should == false + expect(api_client.json_mime?('application/xml')).to eq(false) + expect(api_client.json_mime?('text/plain')).to eq(false) + expect(api_client.json_mime?('application/jsonp')).to eq(false) end end @@ -231,15 +231,15 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new } it "works" do - api_client.select_header_accept(nil).should == nil - api_client.select_header_accept([]).should == nil + expect(api_client.select_header_accept(nil)).to eq(nil) + expect(api_client.select_header_accept([])).to eq(nil) - api_client.select_header_accept(['application/json']).should == 'application/json' - api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' - api_client.select_header_accept(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' + expect(api_client.select_header_accept(['application/json'])).to eq('application/json') + expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') - api_client.select_header_accept(['application/xml']).should == 'application/xml' - api_client.select_header_accept(['text/html', 'application/xml']).should == 'text/html,application/xml' + expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') end end @@ -247,14 +247,14 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new } it "works" do - api_client.select_header_content_type(nil).should == 'application/json' - api_client.select_header_content_type([]).should == 'application/json' + expect(api_client.select_header_content_type(nil)).to eq('application/json') + expect(api_client.select_header_content_type([])).to eq('application/json') - api_client.select_header_content_type(['application/json']).should == 'application/json' - api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' - api_client.select_header_content_type(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' - api_client.select_header_content_type(['application/xml']).should == 'application/xml' - api_client.select_header_content_type(['text/plain', 'application/xml']).should == 'text/plain' + expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') + expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') end end @@ -262,15 +262,15 @@ describe Petstore::ApiClient do let(:api_client) { Petstore::ApiClient.new } it "works" do - api_client.sanitize_filename('sun').should == 'sun' - api_client.sanitize_filename('sun.gif').should == 'sun.gif' - api_client.sanitize_filename('../sun.gif').should == 'sun.gif' - api_client.sanitize_filename('/var/tmp/sun.gif').should == 'sun.gif' - api_client.sanitize_filename('./sun.gif').should == 'sun.gif' - api_client.sanitize_filename('..\sun.gif').should == 'sun.gif' - api_client.sanitize_filename('\var\tmp\sun.gif').should == 'sun.gif' - api_client.sanitize_filename('c:\var\tmp\sun.gif').should == 'sun.gif' - api_client.sanitize_filename('.\sun.gif').should == 'sun.gif' + expect(api_client.sanitize_filename('sun')).to eq('sun') + expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') end end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index eb29b54c2a7..45637e30d6d 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -12,13 +12,13 @@ describe Petstore::Configuration do describe '#base_url' do it 'should have the default value' do - config.base_url.should == 'http://petstore.swagger.io/v2' + expect(config.base_url).to eq('http://petstore.swagger.io/v2') end it 'should remove trailing slashes' do [nil, '', '/', '//'].each do |base_path| config.base_path = base_path - config.base_url.should == 'http://petstore.swagger.io' + expect(config.base_url).to eq('http://petstore.swagger.io') end end end 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 new file mode 100644 index 00000000000..edf0371b127 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/additional_properties_class_spec.rb @@ -0,0 +1,40 @@ +=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 + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::AdditionalPropertiesClass +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'AdditionalPropertiesClass' do + before do + # run before each test + @instance = Petstore::AdditionalPropertiesClass.new + end + + after do + # run after each test + end + + describe 'test an instance of AdditionalPropertiesClass' do + it 'should create an instact of AdditionalPropertiesClass' do + expect(@instance).to be_instance_of(Petstore::AdditionalPropertiesClass) + 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 016b86fd8af..1535c7cb4ec 100644 --- a/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb +++ b/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/animal_spec.rb b/samples/client/petstore/ruby/spec/models/animal_spec.rb index 3f98b0f7b84..5c4f8dc0e69 100644 --- a/samples/client/petstore/ruby/spec/models/animal_spec.rb +++ b/samples/client/petstore/ruby/spec/models/animal_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -42,5 +42,11 @@ describe 'Animal' do 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 + 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 67b0cbe1a03..18ab87bf551 100644 --- a/samples/client/petstore/ruby/spec/models/api_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/api_response_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/array_test_spec.rb b/samples/client/petstore/ruby/spec/models/array_test_spec.rb new file mode 100644 index 00000000000..b0b84f6a4f6 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/array_test_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 + +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. + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ArrayTest +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'ArrayTest' do + before do + # run before each test + @instance = Petstore::ArrayTest.new + end + + after do + # run after each test + end + + describe 'test an instance of ArrayTest' do + it 'should create an instact of ArrayTest' do + expect(@instance).to be_instance_of(Petstore::ArrayTest) + 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 97ae668ea3b..86d600213b3 100644 --- a/samples/client/petstore/ruby/spec/models/cat_spec.rb +++ b/samples/client/petstore/ruby/spec/models/cat_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -42,6 +42,12 @@ describe 'Cat' do 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 + 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 diff --git a/samples/client/petstore/ruby/spec/models/category_spec.rb b/samples/client/petstore/ruby/spec/models/category_spec.rb index 1481358afdc..021de250efc 100644 --- a/samples/client/petstore/ruby/spec/models/category_spec.rb +++ b/samples/client/petstore/ruby/spec/models/category_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/dog_spec.rb b/samples/client/petstore/ruby/spec/models/dog_spec.rb index e3eb4be12fc..10a5b831f25 100644 --- a/samples/client/petstore/ruby/spec/models/dog_spec.rb +++ b/samples/client/petstore/ruby/spec/models/dog_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -42,6 +42,12 @@ describe 'Dog' do 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 + 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 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 b8610d74a1b..02fe0a113fe 100644 --- a/samples/client/petstore/ruby/spec/models/enum_class_spec.rb +++ b/samples/client/petstore/ruby/spec/models/enum_class_spec.rb @@ -1,7 +1,7 @@ =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. +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 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 91941d8a50d..f85c15564f1 100644 --- a/samples/client/petstore/ruby/spec/models/enum_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/enum_test_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -38,19 +38,28 @@ describe 'EnumTest' do end describe 'test attribute "enum_string"' 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 = value }.not_to raise_error + end end end describe 'test attribute "enum_integer"' do it 'should work' do - # 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 - # 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 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 e7a81fe537c..fd6cf6c0381 100644 --- a/samples/client/petstore/ruby/spec/models/format_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/format_test_spec.rb @@ -1,7 +1,7 @@ =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. +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 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 new file mode 100644 index 00000000000..f1f9c33d78f --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/mixed_properties_and_additional_properties_class_spec.rb @@ -0,0 +1,52 @@ +=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 + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::MixedPropertiesAndAdditionalPropertiesClass +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'MixedPropertiesAndAdditionalPropertiesClass' do + before do + # run before each test + @instance = Petstore::MixedPropertiesAndAdditionalPropertiesClass.new + end + + after do + # run after each test + end + + describe 'test an instance of MixedPropertiesAndAdditionalPropertiesClass' do + it 'should create an instact of MixedPropertiesAndAdditionalPropertiesClass' do + expect(@instance).to be_instance_of(Petstore::MixedPropertiesAndAdditionalPropertiesClass) + 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 + 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 + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb index 8b8879105d0..b986604e1ef 100644 --- a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb @@ -1,7 +1,7 @@ =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. +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 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 5a80c97542b..d21f4f1ed3e 100644 --- a/samples/client/petstore/ruby/spec/models/model_return_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_return_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/name_spec.rb b/samples/client/petstore/ruby/spec/models/name_spec.rb index 03a9c69ece1..5ad2a851827 100644 --- a/samples/client/petstore/ruby/spec/models/name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/name_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -54,5 +54,11 @@ describe 'Name' do 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 + 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 73bd5c082fd..008d226ce6e 100644 --- a/samples/client/petstore/ruby/spec/models/order_spec.rb +++ b/samples/client/petstore/ruby/spec/models/order_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -62,7 +62,10 @@ describe 'Order' do describe 'test attribute "status"' 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', ["placed", "approved", "delivered"]) + validator.allowable_values.each do |value| + expect { @instance.status = value }.not_to raise_error + 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 9911ced1366..72780cf80c9 100644 --- a/samples/client/petstore/ruby/spec/models/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/models/pet_spec.rb @@ -1,7 +1,7 @@ =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. +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 @@ -68,7 +68,10 @@ describe 'Pet' do describe 'test attribute "status"' 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', ["available", "pending", "sold"]) + validator.allowable_values.each do |value| + expect { @instance.status = value }.not_to raise_error + 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 new file mode 100644 index 00000000000..ab631729310 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/read_only_first_spec.rb @@ -0,0 +1,52 @@ +=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 + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ReadOnlyFirst +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'ReadOnlyFirst' do + before do + # run before each test + @instance = Petstore::ReadOnlyFirst.new + end + + after do + # run after each test + end + + describe 'test an instance of ReadOnlyFirst' do + it 'should create an instact of ReadOnlyFirst' do + expect(@instance).to be_instance_of(Petstore::ReadOnlyFirst) + end + end + describe 'test attribute "bar"' do + it 'should work' do + # 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 + 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 cd93568e8f9..5b10f4c8f9f 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,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/tag_spec.rb b/samples/client/petstore/ruby/spec/models/tag_spec.rb index 68b77e026b1..c6a5a954b7e 100644 --- a/samples/client/petstore/ruby/spec/models/tag_spec.rb +++ b/samples/client/petstore/ruby/spec/models/tag_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/models/user_spec.rb b/samples/client/petstore/ruby/spec/models/user_spec.rb index fc510605b5c..ae780d5d656 100644 --- a/samples/client/petstore/ruby/spec/models/user_spec.rb +++ b/samples/client/petstore/ruby/spec/models/user_spec.rb @@ -1,7 +1,7 @@ =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. +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 diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 737eee56d07..4ccea494b84 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -33,42 +33,42 @@ describe "Pet" do } pet = Petstore::Pet.new(pet_hash) # test new - pet.name.should == "RUBY UNIT TESTING" - pet.status.should == "pending" - pet.id.should == @pet_id - pet.tags[0].id.should == 1 - pet.tags[1].name.should == 'tag2' - pet.category.name.should == 'category unknown' + expect(pet.name).to eq("RUBY UNIT TESTING") + expect(pet.status).to eq("pending") + expect(pet.id).to eq(@pet_id) + expect(pet.tags[0].id).to eq(1) + expect(pet.tags[1].name).to eq('tag2') + expect(pet.category.name).to eq('category unknown') # test build_from_hash pet2 = Petstore::Pet.new pet2.build_from_hash(pet.to_hash) - pet.to_hash.should == pet2.to_hash + expect(pet.to_hash).to eq(pet2.to_hash) # make sure sub-object has different object id - pet.tags[0].object_id.should_not == pet2.tags[0].object_id - pet.tags[1].object_id.should_not == pet2.tags[1].object_id - pet.category.object_id.should_not == pet2.category.object_id + expect(pet.tags[0].object_id).not_to eq(pet2.tags[0].object_id) + expect(pet.tags[1].object_id).not_to eq(pet2.tags[1].object_id) + expect(pet.category.object_id).not_to eq(pet2.category.object_id) end it "should fetch a pet object" do pet = @pet_api.get_pet_by_id(@pet_id) - pet.should be_a(Petstore::Pet) - pet.id.should == @pet_id - pet.name.should == "RUBY UNIT TESTING" - pet.tags[0].name.should == "tag test" - pet.category.name.should == "category test" + expect(pet).to be_a(Petstore::Pet) + expect(pet.id).to eq(@pet_id) + expect(pet.name).to eq("RUBY UNIT TESTING") + expect(pet.tags[0].name).to eq("tag test") + expect(pet.category.name).to eq("category test") end it "should fetch a pet object with http info" do pet, status_code, headers = @pet_api.get_pet_by_id_with_http_info(@pet_id) - status_code.should == 200 - headers['Content-Type'].should == 'application/json' - pet.should be_a(Petstore::Pet) - pet.id.should == @pet_id - pet.name.should == "RUBY UNIT TESTING" - pet.tags[0].name.should == "tag test" - pet.category.name.should == "category test" + expect(status_code).to eq(200) + expect(headers['Content-Type']).to eq('application/json') + expect(pet).to be_a(Petstore::Pet) + expect(pet.id).to eq(@pet_id) + expect(pet.name).to eq("RUBY UNIT TESTING") + expect(pet.tags[0].name).to eq("tag test") + expect(pet.category.name).to eq("category test") end it "should not find a pet that does not exist" do @@ -76,11 +76,11 @@ describe "Pet" do @pet_api.get_pet_by_id(-@pet_id) fail 'it should raise error' rescue Petstore::ApiError => e - e.code.should == 404 - e.message.should == 'Not Found' - e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}' - e.response_headers.should be_a(Hash) - e.response_headers['Content-Type'].should == 'application/json' + expect(e.code).to eq(404) + expect(e.message).to eq('Not Found') + expect(e.response_body).to eq('{"code":1,"type":"error","message":"Pet not found"}') + expect(e.response_headers).to be_a(Hash) + expect(e.response_headers['Content-Type']).to eq('application/json') end end @@ -93,12 +93,12 @@ describe "Pet" do @pet_api.add_pet_using_byte_array(body: str) fetched_str = @pet_api.pet_pet_idtesting_byte_arraytrue_get(pet.id) - fetched_str.should be_a(String) + expect(fetched_str).to be_a(String) fetched = deserialize_json(fetched_str, 'Pet') - fetched.should be_a(Petstore::Pet) - fetched.id.should == pet.id - fetched.category.should be_a(Petstore::Category) - fetched.category.name.should == pet.category.name + expect(fetched).to be_a(Petstore::Pet) + expect(fetched.id).to eq(pet.id) + expect(fetched.category).to be_a(Petstore::Category) + expect(fetched.category.name).to eq(pet.category.name) @pet_api.delete_pet(pet.id) end @@ -107,40 +107,40 @@ describe "Pet" do # we will re-enable this after updating the petstore server xit "should get pet in object" do pet = @pet_api.get_pet_by_id_in_object(@pet_id) - pet.should be_a(Petstore::InlineResponse200) - pet.id.should == @pet_id - pet.name.should == "RUBY UNIT TESTING" - pet.category.should be_a(Hash) - pet.category[:id].should == 20002 - pet.category[:name].should == 'category test' + expect(pet).to be_a(Petstore::InlineResponse200) + expect(pet.id).to eq(@pet_id) + expect(pet.name).to eq("RUBY UNIT TESTING") + expect(pet.category).to be_a(Hash) + expect(pet.category[:id]).to eq(20002) + expect(pet.category[:name]).to eq('category test') end it "should update a pet" do pet = @pet_api.get_pet_by_id(@pet_id) - pet.id.should == @pet_id - pet.name.should == "RUBY UNIT TESTING" - pet.status.should == 'pending' + expect(pet.id).to eq(@pet_id) + expect(pet.name).to eq("RUBY UNIT TESTING") + expect(pet.status).to eq('pending') @pet_api.update_pet_with_form(@pet_id, name: 'new name', status: 'sold') fetched = @pet_api.get_pet_by_id(@pet_id) - fetched.id.should == @pet_id - fetched.name.should == "new name" - fetched.status.should == 'sold' + expect(fetched.id).to eq(@pet_id) + expect(fetched.name).to eq("new name") + expect(fetched.status).to eq('sold') end it "should find pets by status" do pets = @pet_api.find_pets_by_status(['available']) - pets.length.should >= 3 + expect(pets.length).to be >= 3 pets.each do |pet| - pet.should be_a(Petstore::Pet) - pet.status.should == 'available' + expect(pet).to be_a(Petstore::Pet) + expect(pet.status).to eq('available') end end it "should not find a pet with invalid status" do pets = @pet_api.find_pets_by_status(['invalid-status']) - pets.length.should == 0 + expect(pets.length).to eq(0) end it "should find a pet by status" do @@ -158,11 +158,11 @@ describe "Pet" do pet = Petstore::Pet.new('id' => id, 'name' => "RUBY UNIT TESTING") result = @pet_api.add_pet(pet) # nothing is returned - result.should be_nil + expect(result).to be_nil pet = @pet_api.get_pet_by_id(id) - pet.id.should == id - pet.name.should == "RUBY UNIT TESTING" + expect(pet.id).to eq(id) + expect(pet.name).to eq("RUBY UNIT TESTING") @pet_api.delete_pet(id) end @@ -170,48 +170,48 @@ describe "Pet" do it "should upload a file to a pet" do result = @pet_api.upload_file(@pet_id, file: File.new('hello.txt')) # ApiResponse is returned - result.should be_a(Petstore::ApiResponse) + expect(result).to be_a(Petstore::ApiResponse) end it "should upload a file with form parameter to a pet" do result = @pet_api.upload_file(@pet_id, file: File.new('hello.txt'), additional_metadata: 'metadata') # ApiResponse is returned - result.should be_a(Petstore::ApiResponse) + expect(result).to be_a(Petstore::ApiResponse) end it "should implement eql? and hash" do pet1 = Petstore::Pet.new pet2 = Petstore::Pet.new - pet1.should == pet2 - pet2.should == pet1 - pet1.eql?(pet2).should == true - pet2.eql?(pet1).should == true - pet1.hash.should == pet2.hash - pet1.should == pet1 - pet1.eql?(pet1).should == true - pet1.hash.should == pet1.hash + expect(pet1).to eq(pet2) + expect(pet2).to eq(pet1) + expect(pet1.eql?(pet2)).to eq(true) + expect(pet2.eql?(pet1)).to eq(true) + expect(pet1.hash).to eq(pet2.hash) + expect(pet1).to eq(pet1) + expect(pet1.eql?(pet1)).to eq(true) + expect(pet1.hash).to eq(pet1.hash) pet1.name = 'really-happy' pet1.photo_urls = ['http://foo.bar.com/1', 'http://foo.bar.com/2'] - pet1.should_not == pet2 - pet2.should_not == pet1 - pet1.eql?(pet2).should == false - pet2.eql?(pet1).should == false - pet1.hash.should_not == pet2.hash - pet1.should == pet1 - pet1.eql?(pet1).should == true - pet1.hash.should == pet1.hash + expect(pet1).not_to eq(pet2) + expect(pet2).not_to eq(pet1) + expect(pet1.eql?(pet2)).to eq(false) + expect(pet2.eql?(pet1)).to eq(false) + expect(pet1.hash).not_to eq(pet2.hash) + expect(pet1).to eq(pet1) + expect(pet1.eql?(pet1)).to eq(true) + expect(pet1.hash).to eq(pet1.hash) pet2.name = 'really-happy' pet2.photo_urls = ['http://foo.bar.com/1', 'http://foo.bar.com/2'] - pet1.should == pet2 - pet2.should == pet1 - pet1.eql?(pet2).should == true - pet2.eql?(pet1).should == true - pet1.hash.should == pet2.hash - pet2.should == pet2 - pet2.eql?(pet2).should == true - pet2.hash.should == pet2.hash + expect(pet1).to eq(pet2) + expect(pet2).to eq(pet1) + expect(pet1.eql?(pet2)).to eq(true) + expect(pet2.eql?(pet1)).to eq(true) + expect(pet1.hash).to eq(pet2.hash) + expect(pet2).to eq(pet2) + expect(pet2.eql?(pet2)).to eq(true) + expect(pet2.hash).to eq(pet2.hash) end end end diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index 229a9dfd40a..cdcaedfe44d 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -9,18 +9,18 @@ describe "Store" do @order_id = prepare_store(@api) item = @api.get_order_by_id(@order_id) - item.id.should == @order_id + expect(item.id).to eq(@order_id) @api.delete_order(@order_id) end it "should featch the inventory" do result = @api.get_inventory - result.should be_a(Hash) - result.should_not be_empty + expect(result).to be_a(Hash) + expect(result).not_to be_empty result.each do |k, v| - k.should be_a(Symbol) - v.should be_a(Integer) + expect(k).to be_a(Symbol) + expect(v).to be_a(Integer) end end @@ -28,11 +28,11 @@ describe "Store" do # will re-enable this after updating the petstore server xit "should featch the inventory in object" do result = @api.get_inventory_in_object - result.should be_a(Hash) - result.should_not be_empty + expect(result).to be_a(Hash) + expect(result).not_to be_empty result.each do |k, v| - k.should be_a(Symbol) - v.should be_a(Integer) + expect(k).to be_a(Symbol) + expect(v).to be_a(Integer) end end end diff --git a/samples/client/petstore/scala/.swagger-codegen-ignore b/samples/client/petstore/scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/scala/.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 +# Thsi 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/scala/LICENSE b/samples/client/petstore/scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/scala/build.gradle b/samples/client/petstore/scala/build.gradle new file mode 100644 index 00000000000..979db7783c4 --- /dev/null +++ b/samples/client/petstore/scala/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-scala-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" +} diff --git a/samples/client/petstore/scala/git_push.sh b/samples/client/petstore/scala/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/scala/git_push.sh +++ b/samples/client/petstore/scala/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + 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="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/scala/gradle.properties b/samples/client/petstore/scala/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/scala/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/scala/gradlew b/samples/client/petstore/scala/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/scala/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/scala/gradlew.bat b/samples/client/petstore/scala/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/scala/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/scala/settings.gradle b/samples/client/petstore/scala/settings.gradle new file mode 100644 index 00000000000..5452c701c0e --- /dev/null +++ b/samples/client/petstore/scala/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-scala-client" \ No newline at end of file diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index f7e82cd1b61..3208eb938d5 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -1,8 +1,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import io.swagger.client.ApiInvoker import io.swagger.client.ApiException diff --git a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/spring-stubs/.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 +# Thsi 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/spring-stubs/LICENSE b/samples/client/petstore/spring-stubs/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/spring-stubs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/spring-stubs/README.md b/samples/client/petstore/spring-stubs/README.md new file mode 100644 index 00000000000..99663f64082 --- /dev/null +++ b/samples/client/petstore/spring-stubs/README.md @@ -0,0 +1,27 @@ + +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` diff --git a/samples/client/petstore/spring-stubs/pom.xml b/samples/client/petstore/spring-stubs/pom.xml new file mode 100644 index 00000000000..975433d48c8 --- /dev/null +++ b/samples/client/petstore/spring-stubs/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + io.swagger + swagger-springboot-server + jar + swagger-springboot-server + 1.0.0 + + 2.4.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + src/main/java + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + \ No newline at end of file diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..d055f19cc23 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,156 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import io.swagger.annotations.*; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "pet", description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/x-www-form-urlencoded", + method = RequestMethod.POST) + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = "application/json", + consumes = "multipart/form-data", + method = RequestMethod.POST) + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..03c07525bb3 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,73 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "store", description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public interface StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..3da36b4c67c --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,114 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.List; + +import io.swagger.annotations.*; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "user", description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..1c0dbbf75a7 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class Category { + + private Long id = null; + private String name = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..818052af3a5 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,85 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..d3754b6e828 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,134 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + + private StatusEnum status = null; + private Boolean complete = false; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..dbfcc186ba7 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,137 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + public enum StatusEnum { + available, pending, sold, + }; + + private StatusEnum status = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..349ef702332 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class Tag { + + private Long id = null; + private String name = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..2ba7d2274aa --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java @@ -0,0 +1,156 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/swift-promisekit/.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 +# Thsi 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/swift/.swagger-codegen-ignore b/samples/client/petstore/swift/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/swift/.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 +# Thsi 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/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift deleted file mode 100644 index 418f1c8512b..00000000000 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ /dev/null @@ -1,21 +0,0 @@ -// APIHelper.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -class APIHelper { - static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { - var destination = [String:AnyObject]() - for (key, nillableValue) in source { - if let value: AnyObject = nillableValue { - destination[key] = value - } - } - - if destination.isEmpty { - return nil - } - return destination - } -} diff --git a/samples/client/petstore/swift/SwaggerClientTests/Podfile b/samples/client/petstore/swift/SwaggerClientTests/Podfile deleted file mode 100644 index 5a8ad460aea..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Podfile +++ /dev/null @@ -1,4 +0,0 @@ -use_frameworks! -source 'https://github.com/CocoaPods/Specs.git' -pod "PetstoreClient", :path => "../" - diff --git a/samples/client/petstore/swift/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift/SwaggerClientTests/Podfile.lock deleted file mode 100644 index 76889714e21..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,39 +0,0 @@ -PODS: - - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): - - OMGHTTPURLRQ/FormURLEncode - - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) - - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.4) - - PromiseKit (~> 3.0.0) - - PromiseKit (3.0.3): - - PromiseKit/Foundation (= 3.0.3) - - PromiseKit/QuartzCore (= 3.0.3) - - PromiseKit/UIKit (= 3.0.3) - - PromiseKit/CorePromise (3.0.3) - - PromiseKit/Foundation (3.0.3): - - OMGHTTPURLRQ (~> 3.1.0) - - PromiseKit/CorePromise - - PromiseKit/QuartzCore (3.0.3): - - PromiseKit/CorePromise - - PromiseKit/UIKit (3.0.3): - - PromiseKit/CorePromise - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: ../ - -SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 - PetstoreClient: c9a3d06cf7954479a767135676406c4922cd3c4a - PromiseKit: 00ec2a219bf5ad2833f95977698e921932b8dfd3 - -COCOAPODS: 0.39.0 diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGFormURLEncode.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGFormURLEncode.h deleted file mode 120000 index 8271dc48ed5..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGFormURLEncode.h +++ /dev/null @@ -1 +0,0 @@ -../../../OMGHTTPURLRQ/Sources/OMGFormURLEncode.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGHTTPURLRQ.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGHTTPURLRQ.h deleted file mode 120000 index e0cf7ca4e47..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGHTTPURLRQ.h +++ /dev/null @@ -1 +0,0 @@ -../../../OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGUserAgent.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGUserAgent.h deleted file mode 120000 index 682de9a9e3e..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGUserAgent.h +++ /dev/null @@ -1 +0,0 @@ -../../../OMGHTTPURLRQ/Sources/OMGUserAgent.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/AnyPromise.h deleted file mode 120000 index 61ce91eb094..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Sources/AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/CALayer+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/CALayer+AnyPromise.h deleted file mode 120000 index 831485ea1ce..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/CALayer+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSError+Cancellation.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSError+Cancellation.h deleted file mode 120000 index 7312b04bea2..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSError+Cancellation.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Sources/NSError+Cancellation.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSNotificationCenter+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSNotificationCenter+AnyPromise.h deleted file mode 120000 index 2890a33e083..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSNotificationCenter+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSURLConnection+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSURLConnection+AnyPromise.h deleted file mode 120000 index fd8271b3404..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSURLConnection+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/PromiseKit.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/PromiseKit.h deleted file mode 120000 index c941a074e11..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/PromiseKit.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Sources/PromiseKit.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIActionSheet+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIActionSheet+AnyPromise.h deleted file mode 120000 index 981d4adb5e6..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIActionSheet+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIAlertView+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIAlertView+AnyPromise.h deleted file mode 120000 index 01b78aa08ab..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIAlertView+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIView+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIView+AnyPromise.h deleted file mode 120000 index 98b020ac2c9..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIView+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/UIKit/UIView+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIViewController+AnyPromise.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIViewController+AnyPromise.h deleted file mode 120000 index 3414608e9be..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIViewController+AnyPromise.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/Umbrella.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/Umbrella.h deleted file mode 120000 index ac976191660..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/Umbrella.h +++ /dev/null @@ -1 +0,0 @@ -../../../PromiseKit/Sources/Umbrella.h \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/SwaggerClientTests/Pods/Manifest.lock deleted file mode 100644 index 76889714e21..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Manifest.lock +++ /dev/null @@ -1,39 +0,0 @@ -PODS: - - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): - - OMGHTTPURLRQ/FormURLEncode - - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) - - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.4) - - PromiseKit (~> 3.0.0) - - PromiseKit (3.0.3): - - PromiseKit/Foundation (= 3.0.3) - - PromiseKit/QuartzCore (= 3.0.3) - - PromiseKit/UIKit (= 3.0.3) - - PromiseKit/CorePromise (3.0.3) - - PromiseKit/Foundation (3.0.3): - - OMGHTTPURLRQ (~> 3.1.0) - - PromiseKit/CorePromise - - PromiseKit/QuartzCore (3.0.3): - - PromiseKit/CorePromise - - PromiseKit/UIKit (3.0.3): - - PromiseKit/CorePromise - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: ../ - -SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 - PetstoreClient: c9a3d06cf7954479a767135676406c4922cd3c4a - PromiseKit: 00ec2a219bf5ad2833f95977698e921932b8dfd3 - -COCOAPODS: 0.39.0 diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift b/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift deleted file mode 100644 index 2b60ca476b9..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift +++ /dev/null @@ -1,20 +0,0 @@ - -/** - Resolves with the first resolving promise from a set of promises. - - ``` - race(promise1, promise2, promise3).then { winner in - //… - } - ``` - - - Returns: A new promise that resolves when the first promise in the provided promises resolves. - - Warning: If any of the provided promises reject, the returned promise is rejected. -*/ -public func race(promises: Promise...) -> Promise { - return Promise(sealant: { resolve in - for promise in promises { - promise.pipe(resolve) - } - }) -} diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig deleted file mode 100644 index baea9f3b46a..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ /dev/null @@ -1,5 +0,0 @@ -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/Alamofire" "${PODS_ROOT}/Headers/Public" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_ROOT = ${SRCROOT} -SKIP_INSTALL = YES \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig deleted file mode 100644 index 13e88fd2ece..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig +++ /dev/null @@ -1,4 +0,0 @@ -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/OMGHTTPURLRQ" "${PODS_ROOT}/Headers/Public" -PODS_ROOT = ${SRCROOT} -SKIP_INSTALL = YES \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig deleted file mode 100644 index f579ebfea5e..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig +++ /dev/null @@ -1,5 +0,0 @@ -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/PetstoreClient" "${PODS_ROOT}/Headers/Public" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_ROOT = ${SRCROOT} -SKIP_INSTALL = YES \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-dummy.m b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-dummy.m deleted file mode 100644 index ade64bd1a9b..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods : NSObject -@end -@implementation PodsDummy_Pods -@end diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-resources.sh b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-resources.sh deleted file mode 100755 index 16774fb4661..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-resources.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/sh -set -e - -mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" - -RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt -> "$RESOURCES_TO_COPY" - -XCASSET_FILES=() - -realpath() { - DIRECTORY="$(cd "${1%/*}" && pwd)" - FILENAME="${1##*/}" - echo "$DIRECTORY/$FILENAME" -} - -install_resource() -{ - case $1 in - *.storyboard) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" - ;; - *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" - ;; - *.framework) - echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - ;; - *.xcdatamodel) - echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" - xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" - ;; - *.xcdatamodeld) - echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" - xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" - ;; - *.xcmappingmodel) - echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\"" - xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm" - ;; - *.xcassets) - ABSOLUTE_XCASSET_FILE=$(realpath "${PODS_ROOT}/$1") - XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") - ;; - /*) - echo "$1" - echo "$1" >> "$RESOURCES_TO_COPY" - ;; - *) - echo "${PODS_ROOT}/$1" - echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" - ;; - esac -} - -mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then - mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" - rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -fi -rm -f "$RESOURCES_TO_COPY" - -if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] -then - case "${TARGETED_DEVICE_FAMILY}" in - 1,2) - TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" - ;; - 1) - TARGET_DEVICE_ARGS="--target-device iphone" - ;; - 2) - TARGET_DEVICE_ARGS="--target-device ipad" - ;; - *) - TARGET_DEVICE_ARGS="--target-device mac" - ;; - esac - - # Find all other xcassets (this unfortunately includes those of path pods and other targets). - OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) - while read line; do - if [[ $line != "`realpath $PODS_ROOT`*" ]]; then - XCASSET_FILES+=("$line") - fi - done <<<"$OTHER_XCASSETS" - - printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -fi diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-umbrella.h b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-umbrella.h deleted file mode 100644 index 21dcfd2c21e..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-umbrella.h +++ /dev/null @@ -1,6 +0,0 @@ -#import - - -FOUNDATION_EXPORT double PodsVersionNumber; -FOUNDATION_EXPORT const unsigned char PodsVersionString[]; - diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.debug.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.debug.xcconfig deleted file mode 100644 index ed219269397..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.debug.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -EMBEDDED_CONTENT_CONTAINS_SWIFT = YES -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/Alamofire.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/PetstoreClient.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/PromiseKit.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "OMGHTTPURLRQ" -framework "PetstoreClient" -framework "PromiseKit" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods -PODS_ROOT = ${SRCROOT}/Pods -SWIFT_INSTALL_OBJC_HEADER = NO \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.modulemap b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.modulemap deleted file mode 100644 index 84134130779..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods { - umbrella header "Pods-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.release.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.release.xcconfig deleted file mode 100644 index ed219269397..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods.release.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -EMBEDDED_CONTENT_CONTAINS_SWIFT = YES -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/Alamofire.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/PetstoreClient.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/PromiseKit.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "OMGHTTPURLRQ" -framework "PetstoreClient" -framework "PromiseKit" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods -PODS_ROOT = ${SRCROOT}/Pods -SWIFT_INSTALL_OBJC_HEADER = NO \ No newline at end of file diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist deleted file mode 100644 index 039da19eb7c..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - org.cocoapods.${PRODUCT_NAME:rfc1034identifier} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 3.0.3 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig b/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig deleted file mode 100644 index 66f974aa5ca..00000000000 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig +++ /dev/null @@ -1,7 +0,0 @@ -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/PromiseKit" "${PODS_ROOT}/Headers/Public" -OTHER_LDFLAGS = -framework "Foundation" -framework "QuartzCore" -framework "UIKit" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_ROOT = ${SRCROOT} -SKIP_INSTALL = YES -SWIFT_INSTALL_OBJC_HEADER = NO \ No newline at end of file diff --git a/samples/client/petstore/swift/default/Cartfile b/samples/client/petstore/swift/default/Cartfile new file mode 100644 index 00000000000..3d90db16891 --- /dev/null +++ b/samples/client/petstore/swift/default/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/default/PetstoreClient.podspec similarity index 69% rename from samples/client/petstore/swift/PetstoreClient.podspec rename to samples/client/petstore/swift/default/PetstoreClient.podspec index 1c95cf1afe5..86fa60dd1c6 100644 --- a/samples/client/petstore/swift/PetstoreClient.podspec +++ b/samples/client/petstore/swift/default/PetstoreClient.podspec @@ -4,8 +4,10 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '0.0.1' s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = s.license = 'Apache License, Version 2.0' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' - s.dependency 'PromiseKit', '~> 3.0.0' - s.dependency 'Alamofire', '~> 3.1.4' + s.dependency 'Alamofire', '~> 3.1.5' end diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..7041709f365 --- /dev/null +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,39 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + } + return destination + } + +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 00000000000..6e4ddc4227b --- /dev/null +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,451 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class PetAPI: APIBase { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Add a new pet to the store + - POST /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + + - returns: RequestBuilder + */ + public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma seperated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example={ + "name" : "Puma", + "type" : "Dog", + "color" : "Black", + "gender" : "Female", + "breed" : "Mixed" +}}] + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Finds Pets by tags + - GET /pet/findByTags + - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + + - parameter tags: (query) Tags to filter by (optional) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "tags": tags + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + - OAuth: + - type: oauth2 + - name: petstore_auth + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + + - parameter petId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Update an existing pet + - PUT /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "name": name, + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + + - returns: RequestBuilder + */ + public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 00000000000..362dc968182 --- /dev/null +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,226 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class StoreAPI: APIBase { + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Delete purchase order by ID + - DELETE /store/order/{orderId} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + - parameter orderId: (path) ID of the order that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "key" : 123 +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ + "key" : 123 +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + + - returns: RequestBuilder<[String:Int32]> + */ + public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Find purchase order by ID + - GET /store/order/{orderId} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func placeOrder(body body: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + + - parameter body: (body) order placed for purchasing the pet (optional) + + - returns: RequestBuilder + */ + public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 00000000000..d6df7754683 --- /dev/null +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,344 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class UserAPI: APIBase { + /** + Create user + + - parameter body: (body) Created user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object (optional) + + - returns: RequestBuilder + */ + public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) The name that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Get user by user name + + - 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 + */ + public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + string + string + string + string + string + string + 0 +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + string + string + string + string + string + string + 0 +}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + + /** + Logs user into the system + - GET /user/login + - + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + + - returns: RequestBuilder + */ + public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "username": username, + "password": password + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func logoutUser(completion: ((error: ErrorType?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + public class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + + - returns: RequestBuilder + */ + public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..fed87969388 --- /dev/null +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,74 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + + diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift similarity index 95% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index 0aa3b3e381c..cad60a236a7 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -34,26 +34,26 @@ public class Response { private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary } - + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if T.self is Int32.Type && source is NSNumber { @@ -65,7 +65,7 @@ class Decoders { if source is T { return source as! T } - + let key = "\(T.self)" if let decoder = decoders[key] { return decoder(source) as! T @@ -100,14 +100,15 @@ class Decoders { Decoders.decode(clazz: clazz, source: someSource) } } - + static private func initialize() { dispatch_once(&once) { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'" + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() formatter.dateFormat = format @@ -121,7 +122,7 @@ class Decoders { return date } } - + } if let sourceInt = source as? Int { // treat as a java date @@ -156,7 +157,7 @@ class Decoders { instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) - instance.status = Order.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) return instance } @@ -175,7 +176,7 @@ class Decoders { instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) - instance.status = Pet.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") return instance } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Category.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Category.swift diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Order.swift similarity index 94% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Order.swift index e4086143266..87b2a2c5247 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -9,7 +9,7 @@ import Foundation public class Order: JSONEncodable { - public enum ST: String { + public enum Status: String { case Placed = "placed" case Approved = "approved" case Delivered = "delivered" @@ -19,7 +19,7 @@ public class Order: JSONEncodable { public var quantity: Int32? public var shipDate: NSDate? /** Order Status */ - public var status: ST? + public var status: Status? public var complete: Bool? public init() {} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift similarity index 94% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift index ee9aa295a53..ebcd2c1825f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -9,7 +9,7 @@ import Foundation public class Pet: JSONEncodable { - public enum ST: String { + public enum Status: String { case Available = "available" case Pending = "pending" case Sold = "sold" @@ -20,7 +20,7 @@ public class Pet: JSONEncodable { public var photoUrls: [String]? public var tags: [Tag]? /** pet status in the store */ - public var status: ST? + public var status: Status? public init() {} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/User.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift rename to samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models/User.swift diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Podfile b/samples/client/petstore/swift/default/SwaggerClientTests/Podfile new file mode 100644 index 00000000000..218aae4920f --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Podfile @@ -0,0 +1,11 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Podfile.lock new file mode 100644 index 00000000000..b369a60a1bb --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Podfile.lock @@ -0,0 +1,19 @@ +PODS: + - Alamofire (3.1.5) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.1.5) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 + PetstoreClient: 65dabd411c65d965d5b4c3d5decb909323d1363b + +PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 + +COCOAPODS: 1.0.0 diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/LICENSE rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/README.md rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json similarity index 70% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index fd3d9ad5511..069b678d88c 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -10,13 +10,13 @@ "tag": "v1.0.0" }, "license": "Apache License, Version 2.0", + "authors": "Apache License, Version 2.0", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", "dependencies": { - "PromiseKit": [ - "~> 3.0.0" - ], "Alamofire": [ - "~> 3.1.4" + "~> 3.1.5" ] } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 00000000000..b369a60a1bb --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,19 @@ +PODS: + - Alamofire (3.1.5) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.1.5) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 + PetstoreClient: 65dabd411c65d965d5b4c3d5decb909323d1363b + +PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 + +COCOAPODS: 1.0.0 diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..98d247e012c --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,999 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */; }; + 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */; }; + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; + 1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; + 2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; + 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; + 39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; + 3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; + 45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */; }; + 562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; + 59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; + 7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; + 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */; }; + 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */; }; + 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */; }; + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; + 93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; + A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */; }; + A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */; }; + A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */; }; + B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */; }; + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779B19103BE8402A434ED95F67573911 /* Validation.swift */; }; + C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; + D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */; }; + D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; + D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */; }; + DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */; }; + FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 319E90B185211EB0F7DB65C268512703 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 757F9BBABE83623770250F65EAEE4FD6; + remoteInfo = PetstoreClient; + }; + 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteInfo = Alamofire; + }; + 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteInfo = Alamofire; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; 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 = ""; }; + 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; 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; }; + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 779B19103BE8402A434ED95F67573911 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2A7053C6AF6D6D7610A715632949C369 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F9AF472C2BBE112ACE182D6EA2B243E6 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */, + 37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */, + ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */, + 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */, + 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */, + 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */, + 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */, + FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */, + 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */, + F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */, + 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */, + 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */, + C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */, + 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */, + 779B19103BE8402A434ED95F67573911 /* Validation.swift */, + 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { + isa = PBXGroup; + children = ( + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */, + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */, + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */, + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */, + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */, + ); + path = Models; + sourceTree = ""; + }; + 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */ = { + isa = PBXGroup; + children = ( + 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */, + ); + name = Pods; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 3332D79FDC0D66D4DF418974F676C0C0 /* iOS */ = { + isa = PBXGroup; + children = ( + 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */ = { + isa = PBXGroup; + children = ( + 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */, + 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */, + 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */, + E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */, + 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */, + 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */, + 3332D79FDC0D66D4DF418974F676C0C0 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + 59B91F212518421F271EBA85D5530651 /* Frameworks */, + 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */, + 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + 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 = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */ = { + isa = PBXGroup; + children = ( + 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */, + 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */, + 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */, + EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */, + ); + name = Products; + sourceTree = ""; + }; + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { + isa = PBXGroup; + children = ( + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, + ); + path = Classes; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + 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 */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */, + ); + path = PetstoreClient; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */ = { + isa = PBXGroup; + children = ( + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */, + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */, + D8072E1108951F272C003553FC8926C7 /* APIs.swift */, + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */, + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */, + F92EFB558CBA923AB1CFA22F708E315A /* APIs */, + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */, + ); + path = Swaggers; + sourceTree = ""; + }; + F92EFB558CBA923AB1CFA22F708E315A /* APIs */ = { + isa = PBXGroup; + children = ( + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */, + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */, + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */, + ); + path = APIs; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = A255A180370C09C28653A0EC123D2678 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */, + 2A7053C6AF6D6D7610A715632949C369 /* Frameworks */, + 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */, + A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, + A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, + 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; + 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + 34DFD8BA276C55B95699DFE7BF816A04 /* Sources */, + F9AF472C2BBE112ACE182D6EA2B243E6 /* Frameworks */, + 6C794A7763C2F85750D66CDD002E271F /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */, + 01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */, + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 0529825EC79AED06C77091DC0F061854 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 34DFD8BA276C55B95699DFE7BF816A04 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */, + 7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */, + 59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */, + 121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */, + D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */, + 1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */, + DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */, + CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */, + 909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */, + 45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */, + 562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */, + 39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */, + 93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */, + 2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, + B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, + A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, + D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, + A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, + 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, + 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, + FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, + 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, + D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, + 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, + 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, + FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, + 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, + C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + targetProxy = 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */; + }; + A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + targetProxy = 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */; + }; + A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */; + targetProxy = 319E90B185211EB0F7DB65C268512703 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 51E864C21FD4E8BF48B7DE196DE05017 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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 = YES; + 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_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 7C4A68800C97518F39692FF062F013EE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 84FD87D359382A37B07149A12641B965 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = 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_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + 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; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 95F68EBF32996F2AC8422FE5C210682D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9B26D3A39011247999C097562A550399 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + B316166B7E92675830371A4D5A9C5B6B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F594C655D48020EC34B00AA63E001773 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = 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_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + 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; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FCA939A415B281DBA1BE816C25790182 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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 = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */, + FCA939A415B281DBA1BE816C25790182 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84FD87D359382A37B07149A12641B965 /* Debug */, + F594C655D48020EC34B00AA63E001773 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B316166B7E92675830371A4D5A9C5B6B /* Debug */, + 95F68EBF32996F2AC8422FE5C210682D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, + 9B26D3A39011247999C097562A550399 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A255A180370C09C28653A0EC123D2678 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 51E864C21FD4E8BF48B7DE196DE05017 /* Debug */, + 7C4A68800C97518F39692FF062F013EE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 00000000000..772ef0b2bca --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +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_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist similarity index 92% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist index 93987c18ff5..c1aea25c248 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.${PRODUCT_NAME:rfc1034identifier} + ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist similarity index 92% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist index 94e53826685..cba258550bd 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.${PRODUCT_NAME:rfc1034identifier} + ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig new file mode 100644 index 00000000000..323b0fc6f1d --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -0,0 +1,10 @@ +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_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist similarity index 92% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Info.plist rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist index 69745425863..2243fe6e27d 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Info.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.${PRODUCT_NAME:rfc1034identifier} + ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown new file mode 100644 index 00000000000..a2e64b18120 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -0,0 +1,26 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist new file mode 100644 index 00000000000..d60cd29321b --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -0,0 +1,56 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m new file mode 100644 index 00000000000..6236440163b --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClient : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClient +@end diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-frameworks.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh similarity index 84% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-frameworks.sh rename to samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh index be3c5c77d9f..d3d3acc3025 100755 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-frameworks.sh +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -16,7 +16,7 @@ install_framework() local source="$1" fi - local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." @@ -59,8 +59,8 @@ code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" - /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" fi } @@ -84,14 +84,10 @@ strip_invalid_archs() { if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "Pods/Alamofire.framework" - install_framework "Pods/OMGHTTPURLRQ.framework" - install_framework "Pods/PetstoreClient.framework" - install_framework "Pods/PromiseKit.framework" + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "Pods/Alamofire.framework" - install_framework "Pods/OMGHTTPURLRQ.framework" - install_framework "Pods/PetstoreClient.framework" - install_framework "Pods/PromiseKit.framework" + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" fi diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh new file mode 100755 index 00000000000..e768f92993e --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h new file mode 100644 index 00000000000..b68fbb9611f --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[]; + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig new file mode 100644 index 00000000000..405ae0ee99e --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +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_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_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap new file mode 100644 index 00000000000..ef919b6c0d1 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClient { + umbrella header "Pods-SwaggerClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig new file mode 100644 index 00000000000..405ae0ee99e --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +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_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_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist new file mode 100644 index 00000000000..2243fe6e27d --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown new file mode 100644 index 00000000000..102af753851 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist new file mode 100644 index 00000000000..7acbad1eabb --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m new file mode 100644 index 00000000000..bb17fa2b80f --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClientTests : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClientTests +@end diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh new file mode 100755 index 00000000000..893c16a6313 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh new file mode 100755 index 00000000000..e768f92993e --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h new file mode 100644 index 00000000000..fb4cae0c0fd --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[]; + diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig new file mode 100644 index 00000000000..4078df842f8 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -0,0 +1,7 @@ +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) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap new file mode 100644 index 00000000000..a848da7ffb3 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClientTests { + umbrella header "Pods-SwaggerClientTests-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig new file mode 100644 index 00000000000..4078df842f8 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -0,0 +1,7 @@ +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) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj similarity index 75% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index d65a2a49ff8..3d557a9280f 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -7,7 +7,7 @@ objects = { /* Begin PBXBuildFile section */ - 30ED4051B9A69550250EC1E8 /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C07EC0A94AA0F86D60668B32 /* Pods.framework */; }; + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -16,6 +16,7 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -29,6 +30,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 289E8A9E9C0BB66AD190C7C6 /* 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 = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -41,9 +43,12 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 8A9666BD47569881BB2CE936 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A638467ACFB30852DEA51F7A /* 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 = ""; }; + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - DB0055390ED4A7AE7901DEDD /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -51,7 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 30ED4051B9A69550250EC1E8 /* Pods.framework in Frameworks */, + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -59,17 +64,20 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 0E57353437EAD141ADC443DF /* Pods */ = { + 0CAA98BEFA303B94D3664C7D /* Pods */ = { isa = PBXGroup; children = ( - 8A9666BD47569881BB2CE936 /* Pods.debug.xcconfig */, - DB0055390ED4A7AE7901DEDD /* Pods.release.xcconfig */, + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, ); name = Pods; sourceTree = ""; @@ -78,6 +86,8 @@ isa = PBXGroup; children = ( C07EC0A94AA0F86D60668B32 /* Pods.framework */, + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -88,8 +98,8 @@ 6D4EFB931C692C6300B96B06 /* SwaggerClient */, 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, - 0E57353437EAD141ADC443DF /* Pods */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, + 0CAA98BEFA303B94D3664C7D /* Pods */, ); sourceTree = ""; }; @@ -133,12 +143,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 8FB32D92B81A800A0BF4CD88 /* Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 26CEE7DFCFEEFE9269C60201 /* Embed Pods Frameworks */, - C6760DAD5440B116B9A1DB88 /* Copy Pods Resources */, + 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, ); buildRules = ( ); @@ -153,9 +163,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( + 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, + 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, ); buildRules = ( ); @@ -226,29 +239,29 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 26CEE7DFCFEEFE9269C60201 /* Embed Pods Frameworks */ = { + 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-frameworks.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 8FB32D92B81A800A0BF4CD88 /* Check Pods Manifest.lock */ = { + 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -256,19 +269,64 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - C6760DAD5440B116B9A1DB88 /* Copy Pods Resources */ = { + 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -408,7 +466,7 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8A9666BD47569881BB2CE936 /* Pods.debug.xcconfig */; + baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; @@ -420,7 +478,7 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = DB0055390ED4A7AE7901DEDD /* Pods.release.xcconfig */; + baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; @@ -432,6 +490,7 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; @@ -444,6 +503,7 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/AppDelegate.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/AppDelegate.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/AppDelegate.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Info.plist similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Info.plist rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/Info.plist diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/ViewController.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/ViewController.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/ViewController.swift rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient/ViewController.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/Info.plist similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/Info.plist rename to samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/Info.plist diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift new file mode 100644 index 00000000000..3d3ca03392a --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -0,0 +1,91 @@ +// +// PetAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class PetAPITests: XCTestCase { + + let testTimeout = 10.0 + + 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 test1CreatePet() { + let expectation = self.expectationWithDescription("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 + guard error == nil else { + XCTFail("error creating pet") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test2GetPet() { + let expectation = self.expectationWithDescription("testGetPet") + + PetAPI.getPetById(petId: 1000) { (pet, error) in + guard error == nil else { + XCTFail("error retrieving pet") + return + } + + if let pet = pet { + XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet.name == "Fluffy", "invalid name") + + expectation.fulfill() + } + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test3DeletePet() { + let expectation = self.expectationWithDescription("testDeletePet") + + PetAPI.deletePet(petId: 1000) { (error) in + // The server gives us no data back so Alamofire parsing fails - at least + // verify that is the error we get here + // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero + // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero + // length.} + guard let error = error where error._code == -6006 else { + XCTFail("error deleting pet") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift new file mode 100644 index 00000000000..68232d063d1 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -0,0 +1,98 @@ +// +// StoreAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class StoreAPITests: XCTestCase { + + let testTimeout = 10.0 + + 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 test1PlaceOrder() { + let expectation = self.expectationWithDescription("testPlaceOrder") + + let newOrder = Order() + newOrder.id = 1000 + newOrder.petId = 1000 + newOrder.complete = false + newOrder.quantity = 10 + newOrder.shipDate = NSDate() + // 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 + guard error == nil else { + XCTFail("error placing order") + return + } + + if let order = order { + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .Placed, "invalid status") + + expectation.fulfill() + } + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test2GetOrder() { + let expectation = self.expectationWithDescription("testGetOrder") + + StoreAPI.getOrderById(orderId: "1000") { (order, error) in + guard error == nil else { + XCTFail("error retrieving order") + return + } + + if let order = order { + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .Placed, "invalid status") + + expectation.fulfill() + } + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test3DeleteOrder() { + let expectation = self.expectationWithDescription("testDeleteOrder") + + StoreAPI.deleteOrder(orderId: "1000") { (error) in + // The server gives us no data back so Alamofire parsing fails - at least + // verify that is the error we get here + // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero + // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero + // length.} + guard let error = error where error._code == -6006 else { + XCTFail("error deleting order") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift new file mode 100644 index 00000000000..213e69c56fe --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -0,0 +1,140 @@ +// +// UserAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class UserAPITests: XCTestCase { + + let testTimeout = 10.0 + + 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 testLogin() { + let expectation = self.expectationWithDescription("testLogin") + + UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in + // The server isn't returning JSON - and currently the alamofire implementation + // always parses responses as JSON, so making an exception for this here + // Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." + // UserInfo={NSDebugDescription=Invalid value around character 0.} + guard let error = error where error._code == 3840 else { + XCTFail("error logging in") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func testLogout() { + let expectation = self.expectationWithDescription("testLogout") + + UserAPI.logoutUser { (error) in + // The server gives us no data back so Alamofire parsing fails - at least + // verify that is the error we get here + // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero + // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero + // length.} + guard let error = error where error._code == -6006 else { + XCTFail("error logging out") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test1CreateUser() { + let expectation = self.expectationWithDescription("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 + // The server gives us no data back so Alamofire parsing fails - at least + // verify that is the error we get here + // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero + // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero + // length.} + guard let error = error where error._code == -6006 else { + XCTFail("error creating user") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test2GetUser() { + let expectation = self.expectationWithDescription("testGetUser") + + UserAPI.getUserByName(username: "test@test.com") { (user, error) in + guard error == nil else { + XCTFail("error getting user") + return + } + + if let user = user { + 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() + } + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + + func test3DeleteUser() { + let expectation = self.expectationWithDescription("testDeleteUser") + + UserAPI.deleteUser(username: "test@test.com") { (error) in + // The server gives us no data back so Alamofire parsing fails - at least + // verify that is the error we get here + // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero + // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero + // length.} + guard let error = error where error._code == -6006 else { + XCTFail("error deleting user") + return + } + + expectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift/SwaggerClientTests/pom.xml b/samples/client/petstore/swift/default/SwaggerClientTests/pom.xml similarity index 98% rename from samples/client/petstore/swift/SwaggerClientTests/pom.xml rename to samples/client/petstore/swift/default/SwaggerClientTests/pom.xml index 58c75cb5be1..9eefe4a7a37 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/pom.xml +++ b/samples/client/petstore/swift/default/SwaggerClientTests/pom.xml @@ -54,7 +54,7 @@ SwaggerClient test -destination - platform=iOS Simulator,name=iPhone 6,OS=9.2 + platform=iOS Simulator,name=iPhone 6,OS=9.3 diff --git a/samples/client/petstore/swift/git_push.sh b/samples/client/petstore/swift/default/git_push.sh similarity index 100% rename from samples/client/petstore/swift/git_push.sh rename to samples/client/petstore/swift/default/git_push.sh diff --git a/samples/client/petstore/swift/promisekit/.gitignore b/samples/client/petstore/swift/promisekit/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# 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 + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/.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 +# Thsi 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/swift/Cartfile b/samples/client/petstore/swift/promisekit/Cartfile similarity index 100% rename from samples/client/petstore/swift/Cartfile rename to samples/client/petstore/swift/promisekit/Cartfile diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient.podspec b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec new file mode 100644 index 00000000000..b4eccbce888 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec @@ -0,0 +1,14 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = + s.license = 'Apache License, Version 2.0' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 3.1.1' + s.dependency 'Alamofire', '~> 3.1.5' +end diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..7041709f365 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,39 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + } + return destination + } + +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..96eead0d8dd --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,73 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class PetstoreClientAPI { + public static var basePath = "http://petstore.swagger.io/v2" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(PetstoreClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift similarity index 94% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift rename to samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 64aa3c8803c..c7e5a6402b5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -57,10 +57,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -111,11 +113,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -174,11 +179,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -276,11 +284,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "tags": tags ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -380,11 +391,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -433,10 +447,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -496,11 +512,14 @@ public class PetAPI: APIBase { "name": name, "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -560,11 +579,14 @@ public class PetAPI: APIBase { "additionalMetadata": additionalMetadata, "file": file ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift similarity index 94% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift rename to samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4521afd3d89..be7d36b91f3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -56,11 +56,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -112,11 +115,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -194,11 +200,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -274,10 +283,12 @@ public class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift similarity index 93% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift rename to samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 62018cd83c2..1b5ada9da67 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -54,10 +54,12 @@ public class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -103,10 +105,12 @@ public class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -152,10 +156,12 @@ public class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -203,11 +209,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -293,11 +302,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -352,11 +364,14 @@ public class UserAPI: APIBase { "username": username, "password": password ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -399,11 +414,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -453,10 +471,12 @@ public class UserAPI: APIBase { path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..2faa0a6f24d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,112 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + request.validate().responseJSON(options: .AllowFragments) { response in + managerStore.removeValueForKey(managerId) + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift similarity index 100% rename from samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift rename to samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..cad60a236a7 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,218 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Category] + Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in + return Decoders.decode(clazz: [Category].self, source: source) + } + // Decoder for Category + Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Category() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [Order] + Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in + return Decoders.decode(clazz: [Order].self, source: source) + } + // Decoder for Order + Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Order() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) + instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) + instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) + return instance + } + + + // Decoder for [Pet] + Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in + return Decoders.decode(clazz: [Pet].self, source: source) + } + // Decoder for Pet + Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Pet() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) + instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + return instance + } + + + // Decoder for [Tag] + Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in + return Decoders.decode(clazz: [Tag].self, source: source) + } + // Decoder for Tag + Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Tag() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [User] + Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in + return Decoders.decode(clazz: [User].self, source: source) + } + // Decoder for User + Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = User() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"]) + instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"]) + instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"]) + instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"]) + instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"]) + instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"]) + instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"]) + return instance + } + } + } +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 00000000000..89ce2ccb616 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,25 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Category: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 00000000000..87b2a2c5247 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,39 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Order: JSONEncodable { + public enum Status: String { + case Placed = "placed" + case Approved = "approved" + case Delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: NSDate? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["petId"] = self.petId?.encodeToJSON() + nillableDictionary["quantity"] = self.quantity?.encodeToJSON() + nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + nillableDictionary["complete"] = self.complete + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 00000000000..ebcd2c1825f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,39 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Pet: JSONEncodable { + public enum Status: String { + case Available = "available" + case Pending = "pending" + case Sold = "sold" + } + public var id: Int64? + public var category: Category? + public var name: String? + public var photoUrls: [String]? + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["category"] = self.category?.encodeToJSON() + nillableDictionary["name"] = self.name + nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() + nillableDictionary["tags"] = self.tags?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 00000000000..774f91557e6 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,25 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Tag: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 00000000000..67b72a61922 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,38 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class User: JSONEncodable { + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["username"] = self.username + nillableDictionary["firstName"] = self.firstName + nillableDictionary["lastName"] = self.lastName + nillableDictionary["email"] = self.email + nillableDictionary["password"] = self.password + nillableDictionary["phone"] = self.phone + nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile new file mode 100644 index 00000000000..218aae4920f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile @@ -0,0 +1,11 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock new file mode 100644 index 00000000000..fa9ebeb16ef --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock @@ -0,0 +1,41 @@ +PODS: + - Alamofire (3.1.5) + - OMGHTTPURLRQ (3.1.2): + - OMGHTTPURLRQ/RQ (= 3.1.2) + - OMGHTTPURLRQ/FormURLEncode (3.1.2) + - OMGHTTPURLRQ/RQ (3.1.2): + - OMGHTTPURLRQ/FormURLEncode + - OMGHTTPURLRQ/UserAgent + - OMGHTTPURLRQ/UserAgent (3.1.2) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.1.5) + - PromiseKit (~> 3.1.1) + - PromiseKit (3.1.1): + - PromiseKit/Foundation (= 3.1.1) + - PromiseKit/QuartzCore (= 3.1.1) + - PromiseKit/UIKit (= 3.1.1) + - PromiseKit/CorePromise (3.1.1) + - PromiseKit/Foundation (3.1.1): + - OMGHTTPURLRQ (~> 3.1.0) + - PromiseKit/CorePromise + - PromiseKit/QuartzCore (3.1.1): + - PromiseKit/CorePromise + - PromiseKit/UIKit (3.1.1): + - PromiseKit/CorePromise + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 + OMGHTTPURLRQ: 38316b56d88125c600bcdb16df8329147da2b0ee + PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace + PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb + +PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 + +COCOAPODS: 1.0.0 diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 00000000000..bf300e4482e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 00000000000..bcc0ff4bd05 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1149 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) +[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) + +Alamofire is an HTTP networking library written in Swift. + +## Features + +- [x] Chainable Request / Response methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download using Request or Resume data +- [x] Authentication with NSURLCredential +- [x] HTTP Response Validation +- [x] TLS Certificate and Public Key Pinning +- [x] Progress Closure & NSProgress +- [x] cURL Debug Output +- [x] Comprehensive Unit Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Requirements + +- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 7.2+ + +## Migration Guides + +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** +> +> Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'Alamofire', '~> 3.0' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 3.0 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + +```bash +$ git init +``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + +```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`. + +- And that's it! + +> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +### Response Handling + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseJSON { response in + print(response.request) // original URL request + print(response.response) // URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } + } +``` + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. + +### Response Serialization + +**Built-in Response Methods** + +- `response()` +- `responseData()` +- `responseString(encoding: NSStringEncoding)` +- `responseJSON(options: NSJSONReadingOptions)` +- `responsePropertyList(options: NSPropertyListReadOptions)` + +#### Response Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .response { request, response, data, error in + print(request) + print(response) + print(data) + print(error) + } +``` + +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseData { response in + print(response.request) + print(response.response) + print(response.result) + } +``` + +#### Response String Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") + } +``` + +#### Response JSON Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseJSON { response in + debugPrint(response) + } +``` + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +### HTTP Methods + +`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} +``` + +These values can be passed as the first argument of the `Alamofire.request` method: + +```swift +Alamofire.request(.POST, "https://httpbin.org/post") + +Alamofire.request(.PUT, "https://httpbin.org/put") + +Alamofire.request(.DELETE, "https://httpbin.org/delete") +``` + +### Parameters + +#### GET Request With URL-Encoded Parameters + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) +// https://httpbin.org/get?foo=bar +``` + +#### POST Request With URL-Encoded Parameters + +```swift +let parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters) +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +### Parameter Encoding + +Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: + +```swift +enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) + { ... } +} +``` + +- `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`)._ +- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. +- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. +- `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. + +#### Manual Parameter Encoding of an NSURLRequest + +```swift +let URL = NSURL(string: "https://httpbin.org/get")! +var request = NSMutableURLRequest(URL: URL) + +let parameters = ["foo": "bar"] +let encoding = Alamofire.ParameterEncoding.URL +(request, _) = encoding.encode(request, parameters: parameters) +``` + +#### POST Request with JSON-encoded Parameters + +```swift +let parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +> For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. + +```swift +let headers = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Content-Type": "application/x-www-form-urlencoded" +] + +Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +### Caching + +Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). + +### Uploading + +**Supported Upload Types** + +- File +- Data +- Stream +- MultipartFormData + +#### Uploading a File + +```swift +let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) +``` + +#### Uploading with Progress + +```swift +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) + .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in + print(totalBytesWritten) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes written on main queue: \(totalBytesWritten)") + } + } + .responseJSON { response in + debugPrint(response) + } +``` + +#### Uploading MultipartFormData + +```swift +Alamofire.upload( + .POST, + "https://httpbin.org/post", + multipartFormData: { multipartFormData in + multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") + multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") + }, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .Failure(let encodingError): + print(encodingError) + } + } +) +``` + +### Downloading + +**Supported Download Types** + +- Request +- Resume Data + +#### Downloading a File + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in + let fileManager = NSFileManager.defaultManager() + let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] + let pathComponent = response.suggestedFilename + + return directoryURL.URLByAppendingPathComponent(pathComponent!) +} +``` + +#### Using the Default Download Destination + +```swift +let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +``` + +#### Downloading a File w/Progress + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in + print(totalBytesRead) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes read on main queue: \(totalBytesRead)") + } + } + .response { _, _, _, error in + if let error = error { + print("Failed with error: \(error)") + } else { + print("Downloaded file successfully") + } + } +``` + +#### Accessing Resume Data for Failed Downloads + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .response { _, _, data, _ in + if let + data = data, + resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } + } +``` + +> The `data` parameter is automatically populated with the `resumeData` if available. + +```swift +let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +download.response { _, _, _, _ in + if let + resumeData = download.resumeData, + resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } +} +``` + +### Authentication + +Authentication is handled on the system framework level by [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! +let base64Credentials = credentialData.base64EncodedStringWithOptions([]) + +let headers = ["Authorization": "Basic \(base64Credentials)"] + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with NSURLCredential + +```swift +let user = "user" +let password = "password" + +let credential = NSURLCredential(user: user, password: password, persistence: .ForSession) + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + +### Printable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +### DebugPrintable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + +debugPrint(request) +``` + +#### Output (cURL) + +```bash +$ curl -i \ + -H "User-Agent: Alamofire" \ + -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +> Alamofire is built on `NSURLSession` and the Foundation URL Loading System. To make the most of +this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [NSURLSession Class Reference](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/occ/cl/NSURLSession) +- [NSURLCache Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache) +- [NSURLAuthenticationChallenge Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html) + +### Manager + +Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +```swift +let manager = Alamofire.Manager.sharedInstance +manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)) +``` + +Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`HTTPAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Manager with Default Configuration + +```swift +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Background Configuration + +```swift +let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background") +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Ephemeral Configuration + +```swift +let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Modifying Session Configuration + +```swift +var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +configuration.HTTPAdditionalHeaders = defaultHeaders + +let manager = Alamofire.Manager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Request + +The result of a `request`, `upload`, or `download` method is an instance of `Alamofire.Request`. A request is always created using a constructor method from an owning manager, and never initialized directly. + +Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate chaining. + +Requests can be suspended, resumed, and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Response Serialization + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension Request { + public static func XMLResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let XML = try ONOXMLDocument(data: validData) + return .Success(XML) + } catch { + return .Failure(error as NSError) + } + } + } + + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +public protocol ResponseObjectSerializable { + init?(response: NSHTTPURLResponse, representation: AnyObject) +} + +extension Request { + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONResponseSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let + response = response, + responseObject = T(response: response, representation: value) + { + return .Success(responseObject) + } else { + let failureReason = "JSON could not be serialized into response object: \(value)" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(error) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "https://example.com/users/mattt") + .responseObject { (response: Response) in + debugPrint(response) + } +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +public protocol ResponseCollectionSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] +} + +extension Alamofire.Request { + public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let response = response { + return .Success(T.collection(response: response, representation: value)) + } else { + let failureReason = "Response collection could not be serialized due to nil response" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(error) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable, ResponseCollectionSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } + + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { + var users: [User] = [] + + if let representation = representation as? [[String: AnyObject]] { + for userRepresentation in representation { + if let user = User(response: response, representation: userRepresentation) { + users.append(user) + } + } + } + + return users + } +} +``` + +```swift +Alamofire.request(.GET, "http://example.com/users") + .responseCollection { (response: Response<[User], NSError>) in + debugPrint(response) + } +``` + +### URLStringConvertible + +Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. `NSString`, `NSURL`, `NSURLComponents`, and `NSURLRequest` conform to `URLStringConvertible` by default, allowing any of them to be passed as `URLString` parameters to the `request`, `upload`, and `download` methods: + +```swift +let string = NSString(string: "https://httpbin.org/post") +Alamofire.request(.POST, string) + +let URL = NSURL(string: string)! +Alamofire.request(.POST, URL) + +let URLRequest = NSURLRequest(URL: URL) +Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest` + +let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) +Alamofire.request(.POST, URLComponents) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources. + +#### Type-Safe Routing + +```swift +extension User: URLStringConvertible { + static let baseURLString = "http://example.com" + + var URLString: String { + return User.baseURLString + "/users/\(username)/" + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(.GET, user) // http://example.com/users/mattt +``` + +### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `NSURLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let URL = NSURL(string: "https://httpbin.org/post")! +let mutableURLRequest = NSMutableURLRequest(URL: URL) +mutableURLRequest.HTTPMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) +} catch { + // No-op +} + +mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(mutableURLRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +#### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static let perPage = 50 + + case Search(query: String, page: Int) + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let result: (path: String, parameters: [String: AnyObject]) = { + switch self { + case .Search(let query, let page) where page > 1: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case .Search(let query, _): + return ("/search", ["q": query]) + } + }() + + let URL = NSURL(string: Router.baseURLString)! + let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) + let encoding = Alamofire.ParameterEncoding.URL + + return encoding.encode(URLRequest, parameters: result.parameters).0 + } +} +``` + +```swift +Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50 +``` + +#### CRUD & Authorization + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static var OAuthToken: String? + + case CreateUser([String: AnyObject]) + case ReadUser(String) + case UpdateUser(String, [String: AnyObject]) + case DestroyUser(String) + + var method: Alamofire.Method { + switch self { + case .CreateUser: + return .POST + case .ReadUser: + return .GET + case .UpdateUser: + return .PUT + case .DestroyUser: + return .DELETE + } + } + + var path: String { + switch self { + case .CreateUser: + return "/users" + case .ReadUser(let username): + return "/users/\(username)" + case .UpdateUser(let username, _): + return "/users/\(username)" + case .DestroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let URL = NSURL(string: Router.baseURLString)! + let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) + mutableURLRequest.HTTPMethod = method.rawValue + + if let token = Router.OAuthToken { + mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + + switch self { + case .CreateUser(let parameters): + return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 + case .UpdateUser(_, let parameters): + return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 + default: + return mutableURLRequest + } + } +} +``` + +```swift +Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. +* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. +* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. +* `CustomEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .DisableEvaluation +] + +let manager = Manager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated. + +These server trust policies will result in the following behavior: + +* `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + * Certificate chain MUST be valid. + * Certificate chain MUST include one of the pinned certificates. + * Challenge host MUST match the host in the certificate chain's leaf certificate. +* `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +* All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +--- + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. + +## Open Rdars + +The following rdars have some affect on the current implementation of Alamofire. + +* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 00000000000..b866f42264f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,368 @@ +// Alamofire.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - URLStringConvertible + +/** + Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to + construct URL requests. +*/ +public protocol URLStringConvertible { + /** + A URL that conforms to RFC 2396. + + Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. + + See https://tools.ietf.org/html/rfc2396 + See https://tools.ietf.org/html/rfc1738 + See https://tools.ietf.org/html/rfc1808 + */ + var URLString: String { get } +} + +extension String: URLStringConvertible { + public var URLString: String { + return self + } +} + +extension NSURL: URLStringConvertible { + public var URLString: String { + return absoluteString + } +} + +extension NSURLComponents: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +extension NSURLRequest: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +// MARK: - URLRequestConvertible + +/** + Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +*/ +public protocol URLRequestConvertible { + /// The URL request. + var URLRequest: NSMutableURLRequest { get } +} + +extension NSURLRequest: URLRequestConvertible { + public var URLRequest: NSMutableURLRequest { + return self.mutableCopy() as! NSMutableURLRequest + } +} + +// MARK: - Convenience + +func URLRequest( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil) + -> NSMutableURLRequest +{ + let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + mutableURLRequest.HTTPMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) + } + } + + return mutableURLRequest +} + +// MARK: - Request Methods + +/** + Creates a request using the shared manager instance for the specified method, URL string, parameters, and + parameter encoding. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. +*/ +public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request +{ + return Manager.sharedInstance.request( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/** + Creates a request using the shared manager instance for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. +*/ +public func request(URLRequest: URLRequestConvertible) -> Request { + return Manager.sharedInstance.request(URLRequest.URLRequest) +} + +// MARK: - Upload Methods + +// MARK: File + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and file. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and file. + + - parameter URLRequest: The URL request. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return Manager.sharedInstance.upload(URLRequest, file: file) +} + +// MARK: Data + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and data. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and data. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return Manager.sharedInstance.upload(URLRequest, data: data) +} + +// MARK: Stream + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and stream. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and stream. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return Manager.sharedInstance.upload(URLRequest, stream: stream) +} + +// MARK: MultipartFormData + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + method, + URLString, + headers: headers, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + URLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +// MARK: - Download Methods + +// MARK: URL Request + +/** + Creates a download request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request +{ + return Manager.sharedInstance.download( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers, + destination: destination + ) +} + +/** + Creates a download request using the shared manager instance for the specified URL request. + + - parameter URLRequest: The URL request. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(URLRequest, destination: destination) +} + +// MARK: Resume Data + +/** + Creates a request using the shared manager instance for downloading from the resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(data, destination: destination) +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift new file mode 100644 index 00000000000..b9a043cb8e3 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -0,0 +1,244 @@ +// Download.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Manager { + private enum Downloadable { + case Request(NSURLRequest) + case ResumeData(NSData) + } + + private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { + var downloadTask: NSURLSessionDownloadTask! + + switch downloadable { + case .Request(let request): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithRequest(request) + } + case .ResumeData(let resumeData): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithResumeData(resumeData) + } + } + + let request = Request(session: session, task: downloadTask) + + if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { + downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in + return destination(URL, downloadTask.response as! NSHTTPURLResponse) + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: Request + + /** + Creates a download request for the specified method, URL string, parameters, parameter encoding, headers + and destination. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + + return download(encodedURLRequest, destination: destination) + } + + /** + Creates a request for downloading from the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return download(.Request(URLRequest.URLRequest), destination: destination) + } + + // MARK: Resume Data + + /** + Creates a request for downloading from the resume data produced from a previous request cancellation. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for + additional information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { + return download(.ResumeData(resumeData), destination: destination) + } +} + +// MARK: - + +extension Request { + /** + A closure executed once a request has successfully completed in order to determine where to move the temporary + file written to during the download process. The closure takes two arguments: the temporary file URL and the URL + response, and returns a single argument: the file URL where the temporary file should be moved. + */ + public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL + + /** + Creates a download file destination closure which uses the default file manager to move the temporary file to a + file URL in the first available directory with the specified search path directory and search path domain mask. + + - parameter directory: The search path directory. `.DocumentDirectory` by default. + - parameter domain: The search path domain mask. `.UserDomainMask` by default. + + - returns: A download file destination closure. + */ + public class func suggestedDownloadDestination( + directory directory: NSSearchPathDirectory = .DocumentDirectory, + domain: NSSearchPathDomainMask = .UserDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response -> NSURL in + let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) + + if !directoryURLs.isEmpty { + return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) + } + + return temporaryURL + } + } + + /// The resume data of the underlying download task if available after a failure. + public var resumeData: NSData? { + var data: NSData? + + if let delegate = delegate as? DownloadTaskDelegate { + data = delegate.resumeData + } + + return data + } + + // MARK: - DownloadTaskDelegate + + class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { + var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } + var downloadProgress: ((Int64, Int64, Int64) -> Void)? + + var resumeData: NSData? + override var data: NSData? { return resumeData } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? + var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + do { + let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) + } catch { + self.error = error as NSError + } + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift new file mode 100644 index 00000000000..7a813f1b813 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -0,0 +1,66 @@ +// Error.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. +public struct Error { + /// The domain used for creating all Alamofire errors. + public static let Domain = "com.alamofire.error" + + /// The custom error codes generated by Alamofire. + public enum Code: Int { + case InputStreamReadFailed = -6000 + case OutputStreamWriteFailed = -6001 + case ContentTypeValidationFailed = -6002 + case StatusCodeValidationFailed = -6003 + case DataSerializationFailed = -6004 + case StringSerializationFailed = -6005 + case JSONSerializationFailed = -6006 + case PropertyListSerializationFailed = -6007 + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + public static func errorWithCode(code: Code, failureReason: String) -> NSError { + return errorWithCode(code.rawValue, failureReason: failureReason) + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + public static func errorWithCode(code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: Domain, code: code, userInfo: userInfo) + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift new file mode 100644 index 00000000000..d81c7380fa8 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -0,0 +1,693 @@ +// Manager.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +*/ +public class Manager { + + // MARK: - Properties + + /** + A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly + for any ad hoc requests. + */ + public static let sharedInstance: Manager = { + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders + + return Manager(configuration: configuration) + }() + + /** + Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + */ + public static let defaultHTTPHeaders: [String: String] = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joinWithSeparator(", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + let userAgent: String = { + if let info = NSBundle.mainBundle().infoDictionary { + let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" + let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" + let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" + let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + + var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString + let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + + if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { + return mutableUserAgent as String + } + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) + + /// The underlying session. + public let session: NSURLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + public var startRequestsImmediately: Bool = true + + /** + The background completion handler closure provided by the UIApplicationDelegate + `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + will automatically call the handler. + + If you need to handle your own events before the handler is called, then you need to override the + SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + + `nil` by default. + */ + public var backgroundCompletionHandler: (() -> Void)? + + // MARK: - Lifecycle + + /** + Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. + + - parameter configuration: The configuration used to construct the managed session. + `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. + - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + default. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance. + */ + public init( + configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /** + Initializes the `Manager` instance with the specified session, delegate and server trust policy. + + - parameter session: The URL session. + - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. + */ + public init?( + session: NSURLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = session + + guard delegate === session.delegate else { return nil } + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Request + + /** + Creates a request for the specified method, URL string, parameters, parameter encoding and headers. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. + */ + public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + return request(encodedURLRequest) + } + + /** + Creates a request for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. + */ + public func request(URLRequest: URLRequestConvertible) -> Request { + var dataTask: NSURLSessionDataTask! + dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } + + let request = Request(session: session, task: dataTask) + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: - SessionDelegate + + /** + Responsible for handling all delegate callbacks for the underlying session. + */ + public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + private var subdelegates: [Int: Request.TaskDelegate] = [:] + private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + + subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + get { + var subdelegate: Request.TaskDelegate? + dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } + + return subdelegate + } + + set { + dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } + } + } + + /** + Initializes the `SessionDelegate` instance. + + - returns: The new `SessionDelegate` instance. + */ + public override init() { + super.init() + } + + // MARK: - NSURLSessionDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. + public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. + public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. + public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the session has been invalidated. + + - parameter session: The session object that was invalidated. + - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + */ + public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /** + Requests credentials from the delegate in response to a session-level authentication request from the remote server. + + - parameter session: The session containing the task that requested authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + + /** + Tells the delegate that all messages enqueued for a session have been delivered. + + - parameter session: The session that no longer has any outstanding requests. + */ + public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. + public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. + public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. + public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the remote server requested an HTTP redirect. + + - parameter session: The session containing the task whose request resulted in a redirect. + - parameter task: The task whose request resulted in a redirect. + - parameter response: An object containing the server’s response to the original request. + - parameter request: A URL request object filled out with the new location. + - parameter completionHandler: A closure that your handler should call with either the value of the request + parameter, a modified URL request object, or NULL to refuse the redirect and + return the body of the redirect response. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /** + Requests credentials from the delegate in response to an authentication request from the remote server. + + - parameter session: The session containing the task whose request requires authentication. + - parameter task: The task whose request requires authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + completionHandler(taskDidReceiveChallenge(session, task, challenge)) + } else if let delegate = self[task] { + delegate.URLSession( + session, + task: task, + didReceiveChallenge: challenge, + completionHandler: completionHandler + ) + } else { + URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) + } + } + + /** + Tells the delegate when a task requires a new request body stream to send to the remote server. + + - parameter session: The session containing the task that needs a new body stream. + - parameter task: The task that needs a new body stream. + - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /** + Periodically informs the delegate of the progress of sending body content to the server. + + - parameter session: The session containing the data task. + - parameter task: The data task. + - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + - parameter totalBytesSent: The total number of bytes sent so far. + - parameter totalBytesExpectedToSend: The expected length of the body data. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task] as? Request.UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + + /** + Tells the delegate that the task finished transferring data. + + - parameter session: The session containing the task whose request finished transferring data. + - parameter task: The task whose request finished transferring data. + - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + */ + public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidComplete = taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, didCompleteWithError: error) + } + + self[task] = nil + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. + public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. + public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the data task received the initial reply (headers) from the server. + + - parameter session: The session containing the data task that received an initial reply. + - parameter dataTask: The data task that received an initial reply. + - parameter response: A URL response object populated with headers. + - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + constant to indicate whether the transfer should continue as a data task or + should become a download task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /** + Tells the delegate that the data task was changed to a download task. + + - parameter session: The session containing the task that was replaced by a download task. + - parameter dataTask: The data task that was replaced by a download task. + - parameter downloadTask: The new download task that replaced the data task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) + self[downloadTask] = downloadDelegate + } + } + + /** + Tells the delegate that the data task has received some of the expected data. + + - parameter session: The session containing the data task that provided data. + - parameter dataTask: The data task that provided data. + - parameter data: A data object containing the transferred data. + */ + public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) + } + } + + /** + Asks the delegate whether the data (or upload) task should store the response in the cache. + + - parameter session: The session containing the data (or upload) task. + - parameter dataTask: The data (or upload) task. + - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + caching policy and the values of certain received headers, such as the Pragma + and Cache-Control headers. + - parameter completionHandler: A block that your handler must call, providing either the original proposed + response, a modified version of that response, or NULL to prevent caching the + response. If your delegate implements this method, it must call this completion + handler; otherwise, your app leaks memory. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. + public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that a download task has finished downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that finished. + - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + open the file for reading or move it to a permanent location in your app’s sandbox + container directory before returning from this delegate method. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) + } + } + + /** + Periodically informs the delegate about the download’s progress. + + - parameter session: The session containing the download task. + - parameter downloadTask: The download task. + - parameter bytesWritten: The number of bytes transferred since the last time this delegate + method was called. + - parameter totalBytesWritten: The total number of bytes transferred so far. + - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + header. If this header was not provided, the value is + `NSURLSessionTransferSizeUnknown`. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /** + Tells the delegate that the download task has resumed downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that resumed. See explanation in the discussion. + - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + existing content, then this value is zero. Otherwise, this value is an + integer representing the number of bytes on disk that do not need to be + retrieved again. + - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } + + // MARK: - NSURLSessionStreamDelegate + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + + // MARK: - NSObject + + public override func respondsToSelector(selector: Selector) -> Bool { + switch selector { + case "URLSession:didBecomeInvalidWithError:": + return sessionDidBecomeInvalidWithError != nil + case "URLSession:didReceiveChallenge:completionHandler:": + return sessionDidReceiveChallenge != nil + case "URLSessionDidFinishEventsForBackgroundURLSession:": + return sessionDidFinishEventsForBackgroundURLSession != nil + case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": + return taskWillPerformHTTPRedirection != nil + case "URLSession:dataTask:didReceiveResponse:completionHandler:": + return dataTaskDidReceiveResponse != nil + default: + return self.dynamicType.instancesRespondToSelector(selector) + } + } + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 00000000000..8c37f164e7e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,669 @@ +// MultipartFormData.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(OSX) +import CoreServices +#endif + +/** + Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode + multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead + to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the + data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for + larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. + + For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well + and the w3 form documentation. + + - https://www.ietf.org/rfc/rfc2388.txt + - https://www.ietf.org/rfc/rfc2045.txt + - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +*/ +public class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let CRLF = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case Initial, Encapsulated, Final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { + let boundaryText: String + + switch boundaryType { + case .Initial: + boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" + case .Encapsulated: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" + case .Final: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" + } + + return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: [String: String] + let bodyStream: NSInputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: NSError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /** + Creates a multipart form data object. + + - returns: The multipart form data object. + */ + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /** + * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + * information, please refer to the following article: + * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + */ + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String) { + let headers = contentHeaders(name: name) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, mimeType: String) { + let headers = contentHeaders(name: name, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + system associated MIME type. + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String) { + if let + fileName = fileURL.lastPathComponent, + pathExtension = fileURL.pathExtension + { + let mimeType = mimeTypeForPathExtension(pathExtension) + appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) + } else { + let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" + setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + } + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + - Content-Type: #{mimeType} (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.fileURL else { + let failureReason = "The file URL does not point to a file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + var isReachable = true + + if #available(OSX 10.10, *) { + isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) + } + + guard isReachable else { + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") + setBodyPartError(error) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + + guard let + path = fileURL.path + where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else + { + let failureReason = "The file URL is a directory, not a file: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + var bodyContentLength: UInt64? + + do { + if let + path = fileURL.path, + fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber + { + bodyContentLength = fileSize.unsignedLongLongValue + } + } catch { + // No-op + } + + guard let length = bodyContentLength else { + let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = NSInputStream(URL: fileURL) else { + let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + setBodyPartError(error) + return + } + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the stream and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + */ + public func appendBodyPart( + stream stream: NSInputStream, + length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part with the headers, stream and length and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - HTTP headers + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter headers: The HTTP headers for the body part. + */ + public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /** + Encodes all the appended body parts into a single `NSData` object. + + It is important to note that this method will load all the appended body parts into memory all at the same + time. This method should only be used when the encoded data will have a small memory footprint. For large data + cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + + - throws: An `NSError` if encoding encounters an error. + + - returns: The encoded `NSData` if encoding is successful. + */ + public func encode() throws -> NSData { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + let encoded = NSMutableData() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encodeBodyPart(bodyPart) + encoded.appendData(encodedData) + } + + return encoded + } + + /** + Writes the appended body parts into the given file URL. + + This process is facilitated by reading and writing with input and output streams, respectively. Thus, + this approach is very memory efficient and should be used for large body part data. + + - parameter fileURL: The file URL to write the multipart form data into. + + - throws: An `NSError` if encoding encounters an error. + */ + public func writeEncodedDataToDisk(fileURL: NSURL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { + let failureReason = "A file already exists at the given file URL: \(fileURL)" + throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + } else if !fileURL.fileURL { + let failureReason = "The URL does not point to a valid file: \(fileURL)" + throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + } + + let outputStream: NSOutputStream + + if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { + outputStream = possibleOutputStream + } else { + let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" + throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + } + + outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + outputStream.open() + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try writeBodyPart(bodyPart, toOutputStream: outputStream) + } + + outputStream.close() + outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + } + + // MARK: - Private - Body Part Encoding + + private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { + let encoded = NSMutableData() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.appendData(initialData) + + let headerData = encodeHeaderDataForBodyPart(bodyPart) + encoded.appendData(headerData) + + let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) + encoded.appendData(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.appendData(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" + } + headerText += EncodingCharacters.CRLF + + return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + + private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { + let inputStream = bodyPart.bodyStream + inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + inputStream.open() + + var error: NSError? + let encoded = NSMutableData() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if inputStream.streamError != nil { + error = inputStream.streamError + break + } + + if bytesRead > 0 { + encoded.appendBytes(buffer, length: bytesRead) + } else if bytesRead < 0 { + let failureReason = "Failed to read from input stream: \(inputStream)" + error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + break + } else { + break + } + } + + inputStream.close() + inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + + if let error = error { + throw error + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) + try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + } + + private func writeInitialBoundaryDataForBodyPart( + bodyPart: BodyPart, + toOutputStream outputStream: NSOutputStream) + throws + { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try writeData(initialData, toOutputStream: outputStream) + } + + private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let headerData = encodeHeaderDataForBodyPart(bodyPart) + return try writeData(headerData, toOutputStream: outputStream) + } + + private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let inputStream = bodyPart.bodyStream + inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + inputStream.open() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw streamError + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0 { + if outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let streamError = outputStream.streamError { + throw streamError + } + + if bytesWritten < 0 { + let failureReason = "Failed to write to output stream: \(outputStream)" + throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if let + id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), + contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(name name: String) -> [String: String] { + return ["Content-Disposition": "form-data; name=\"\(name)\""] + } + + private func contentHeaders(name name: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"", + "Content-Type": "\(mimeType)" + ] + } + + private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", + "Content-Type": "\(mimeType)" + ] + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(error: NSError) { + if bodyPartError == nil { + bodyPartError = error + } + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 00000000000..d56d2d6c3a7 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,251 @@ +// ParameterEncoding.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + HTTP method definitions. + + See https://tools.ietf.org/html/rfc7231#section-4.3 +*/ +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} + +// MARK: ParameterEncoding + +/** + Used to specify the way in which a set of parameters are applied to a URL request. + + - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, + and `DELETE` requests, or set as the body for requests with any other HTTP method. The + `Content-Type` HTTP header field of an encoded request with HTTP body is set to + `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification + for how to encode collection types, the convention of appending `[]` to the key for array + values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested + dictionary values (`foo[bar]=baz`). + + - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same + implementation as the `.URL` case, but always applies the encoded result to the URL. + + - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is + set as the body of the request. The `Content-Type` HTTP header field of an encoded request is + set to `application/json`. + + - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, + according to the associated format and write options values, which is set as the body of the + request. The `Content-Type` HTTP header field of an encoded request is set to + `application/x-plist`. + + - `Custom`: Uses the associated closure value to construct a new request given an existing request and + parameters. +*/ +public enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + /** + Creates a URL request by encoding parameters and applying them onto an existing request. + + - parameter URLRequest: The request to have parameters applied + - parameter parameters: The parameters to apply + + - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, + if any. + */ + public func encode( + URLRequest: URLRequestConvertible, + parameters: [String: AnyObject]?) + -> (NSMutableURLRequest, NSError?) + { + var mutableURLRequest = URLRequest.URLRequest + + guard let parameters = parameters where !parameters.isEmpty else { + return (mutableURLRequest, nil) + } + + var encodingError: NSError? = nil + + switch self { + case .URL, .URLEncodedInURL: + func query(parameters: [String: AnyObject]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sort(<) { + let value = parameters[key]! + components += queryComponents(key, value) + } + + return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") + } + + func encodesParametersInURL(method: Method) -> Bool { + switch self { + case .URLEncodedInURL: + return true + default: + break + } + + switch method { + case .GET, .HEAD, .DELETE: + return true + default: + return false + } + } + + if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { + if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + URLComponents.percentEncodedQuery = percentEncodedQuery + mutableURLRequest.URL = URLComponents.URL + } + } else { + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue( + "application/x-www-form-urlencoded; charset=utf-8", + forHTTPHeaderField: "Content-Type" + ) + } + + mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( + NSUTF8StringEncoding, + allowLossyConversion: false + ) + } + case .JSON: + do { + let options = NSJSONWritingOptions() + let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) + + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .PropertyList(let format, let options): + do { + let data = try NSPropertyListSerialization.dataWithPropertyList( + parameters, + format: format, + options: options + ) + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .Custom(let closure): + (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) + } + + return (mutableURLRequest, encodingError) + } + + /** + Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + + - parameter key: The key of the query component. + - parameter value: The value of the query component. + + - returns: The percent-escaped, URL encoded query string components. + */ + public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: AnyObject] { + for (nestedKey, value) in dictionary { + components += queryComponents("\(key)[\(nestedKey)]", value) + } + } else if let array = value as? [AnyObject] { + for value in array { + components += queryComponents("\(key)[]", value) + } + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + + RFC 3986 states that the following characters are "reserved" characters. + + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + - parameter string: The string to be percent-escaped. + + - returns: The percent-escaped string. + */ + public func escape(string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet + allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, OSX 10.10, *) { + escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = index.advancedBy(batchSize, limit: string.endIndex) + let range = Range(start: startIndex, end: endIndex) + + let substring = string.substringWithRange(range) + + escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring + + index = endIndex + } + } + + return escaped + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift new file mode 100644 index 00000000000..3e242e7ea72 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,538 @@ +// Request.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Responsible for sending a request and receiving the response and associated data from the server, as well as + managing its underlying `NSURLSessionTask`. +*/ +public class Request { + + // MARK: - Properties + + /// The delegate for the underlying task. + public let delegate: TaskDelegate + + /// The underlying task. + public var task: NSURLSessionTask { return delegate.task } + + /// The session belonging to the underlying task. + public let session: NSURLSession + + /// The request sent or to be sent to the server. + public var request: NSURLRequest? { return task.originalRequest } + + /// The response received from the server, if any. + public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } + + /// The progress of the request lifecycle. + public var progress: NSProgress { return delegate.progress } + + // MARK: - Lifecycle + + init(session: NSURLSession, task: NSURLSessionTask) { + self.session = session + + switch task { + case is NSURLSessionUploadTask: + self.delegate = UploadTaskDelegate(task: task) + case is NSURLSessionDataTask: + self.delegate = DataTaskDelegate(task: task) + case is NSURLSessionDownloadTask: + self.delegate = DownloadTaskDelegate(task: task) + default: + self.delegate = TaskDelegate(task: task) + } + } + + // MARK: - Authentication + + /** + Associates an HTTP Basic credential with the request. + + - parameter user: The user. + - parameter password: The password. + - parameter persistence: The URL credential persistence. `.ForSession` by default. + + - returns: The request. + */ + public func authenticate( + user user: String, + password: String, + persistence: NSURLCredentialPersistence = .ForSession) + -> Self + { + let credential = NSURLCredential(user: user, password: password, persistence: persistence) + + return authenticate(usingCredential: credential) + } + + /** + Associates a specified credential with the request. + + - parameter credential: The credential. + + - returns: The request. + */ + public func authenticate(usingCredential credential: NSURLCredential) -> Self { + delegate.credential = credential + + return self + } + + // MARK: - Progress + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is written to or read + from the server. + + - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected + to write. + - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes + expected to read. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { + if let uploadDelegate = delegate as? UploadTaskDelegate { + uploadDelegate.uploadProgress = closure + } else if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataProgress = closure + } else if let downloadDelegate = delegate as? DownloadTaskDelegate { + downloadDelegate.downloadProgress = closure + } + + return self + } + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + + This closure returns the bytes most recently received from the server, not including data from previous calls. + If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + also important to note that the `response` closure will be called with nil `responseData`. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func stream(closure: (NSData -> Void)? = nil) -> Self { + if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataStream = closure + } + + return self + } + + // MARK: - State + + /** + Suspends the request. + */ + public func suspend() { + task.suspend() + } + + /** + Resumes the request. + */ + public func resume() { + task.resume() + } + + /** + Cancels the request. + */ + public func cancel() { + if let + downloadDelegate = delegate as? DownloadTaskDelegate, + downloadTask = downloadDelegate.downloadTask + { + downloadTask.cancelByProducingResumeData { data in + downloadDelegate.resumeData = data + } + } else { + task.cancel() + } + } + + // MARK: - TaskDelegate + + /** + The task delegate is responsible for handling all delegate callbacks for the underlying task as well as + executing all operations attached to the serial operation queue upon task completion. + */ + public class TaskDelegate: NSObject { + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: NSOperationQueue + + let task: NSURLSessionTask + let progress: NSProgress + + var data: NSData? { return nil } + var error: NSError? + + var credential: NSURLCredential? + + init(task: NSURLSessionTask) { + self.task = task + self.progress = NSProgress(totalUnitCount: 0) + self.queue = { + let operationQueue = NSOperationQueue() + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.suspended = true + + if #available(OSX 10.10, *) { + operationQueue.qualityOfService = NSQualityOfService.Utility + } + + return operationQueue + }() + } + + deinit { + queue.cancelAllOperations() + queue.suspended = false + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .CancelAuthenticationChallenge + } else { + credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) + + if credential != nil { + disposition = .UseCredential + } + } + } + + completionHandler(disposition, credential) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + var bodyStream: NSInputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + self.error = error + + if let + downloadDelegate = self as? DownloadTaskDelegate, + userInfo = error.userInfo as? [String: AnyObject], + resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData + { + downloadDelegate.resumeData = resumeData + } + } + + queue.suspended = false + } + } + } + + // MARK: - DataTaskDelegate + + class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { + var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } + + private var totalBytesReceived: Int64 = 0 + private var mutableData: NSMutableData + override var data: NSData? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + private var expectedContentLength: Int64? + private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? + private var dataStream: ((data: NSData) -> Void)? + + override init(task: NSURLSessionTask) { + mutableData = NSMutableData() + super.init(task: task) + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: (NSURLSessionResponseDisposition -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data: data) + } else { + mutableData.appendData(data) + } + + totalBytesReceived += data.length + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + dataProgress?( + bytesReceived: Int64(data.length), + totalBytesReceived: totalBytesReceived, + totalBytesExpectedToReceive: totalBytesExpected + ) + } + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + var cachedResponse: NSCachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + + /** + The textual representation used when written to an output stream, which includes the HTTP method and URL, as + well as the response status code if a response has been received. + */ + public var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.HTTPMethod { + components.append(HTTPMethod) + } + + if let URLString = request?.URL?.absoluteString { + components.append(URLString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joinWithSeparator(" ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + func cURLRepresentation() -> String { + var components = ["$ curl -i"] + + guard let + request = self.request, + URL = request.URL, + host = URL.host + else { + return "$ curl command could not be created" + } + + if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { + components.append("-X \(HTTPMethod)") + } + + if let credentialStorage = self.session.configuration.URLCredentialStorage { + let protectionSpace = NSURLProtectionSpace( + host: host, + port: URL.port?.integerValue ?? 0, + `protocol`: URL.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { + for credential in credentials { + components.append("-u \(credential.user!):\(credential.password!)") + } + } else { + if let credential = delegate.credential { + components.append("-u \(credential.user!):\(credential.password!)") + } + } + } + + if session.configuration.HTTPShouldSetCookies { + if let + cookieStorage = session.configuration.HTTPCookieStorage, + cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } + components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields { + switch field { + case "Cookie": + continue + default: + components.append("-H \"\(field): \(value)\"") + } + } + } + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders { + switch field { + case "Cookie": + continue + default: + components.append("-H \"\(field): \(value)\"") + } + } + } + + if let + HTTPBodyData = request.HTTPBody, + HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) + { + let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(URL.absoluteString)\"") + + return components.joinWithSeparator(" \\\n\t") + } + + /// The textual representation used when written to an output stream, in the form of a cURL command. + public var debugDescription: String { + return cURLRepresentation() + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 00000000000..fa2fffb3dea --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,83 @@ +// Response.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Used to store all response data returned from a completed `Request`. +public struct Response { + /// The URL request sent to the server. + public let request: NSURLRequest? + + /// The server's response to the URL request. + public let response: NSHTTPURLResponse? + + /// The data returned by the server. + public let data: NSData? + + /// The result of response serialization. + public let result: Result + + /** + Initializes the `Response` instance with the specified URL request, URL response, server data and response + serialization result. + + - parameter request: The URL request sent to the server. + - parameter response: The server's response to the URL request. + - parameter data: The data returned by the server. + - parameter result: The result of response serialization. + + - returns: the new `Response` instance. + */ + public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + self.request = request + self.response = response + self.data = data + self.result = result + } +} + +// MARK: - CustomStringConvertible + +extension Response: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } +} + +// MARK: - CustomDebugStringConvertible + +extension Response: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data and the response serialization result. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.length ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + + return output.joinWithSeparator("\n") + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 00000000000..4aaacf61e31 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,355 @@ +// ResponseSerialization.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: ResponseSerializer + +/** + The type in which all response serializers must conform to in order to serialize a response. +*/ +public protocol ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializerType`. + typealias SerializedObject + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + typealias ErrorObject: ErrorType + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } +} + +// MARK: - + +/** + A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. +*/ +public struct ResponseSerializer: ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializer`. + public typealias SerializedObject = Value + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + public typealias ErrorObject = Error + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result + + /** + Initializes the `ResponseSerializer` instance with the given serialize response closure. + + - parameter serializeResponse: The closure used to serialize the response. + + - returns: The new generic response serializer instance. + */ + public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Default + +extension Request { + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + dispatch_async(queue ?? dispatch_get_main_queue()) { + completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) + } + } + + return self + } + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter responseSerializer: The response serializer responsible for serializing the request, response, + and data. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + responseSerializer: T, + completionHandler: Response -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result + ) + + completionHandler(response) + } + } + + return self + } +} + +// MARK: - Data + +extension Request { + + /** + Creates a response serializer that returns the associated data as-is. + + - returns: A data response serializer. + */ + public static func dataResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSData()) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + return .Success(validData) + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func responseData(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - String + +extension Request { + + /** + Creates a response serializer that returns a string initialized from the response data with the specified + string encoding. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + response, falling back to the default HTTP default character set, ISO-8859-1. + + - returns: A string response serializer. + */ + public static func stringResponseSerializer( + var encoding encoding: NSStringEncoding? = nil) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success("") } + + guard let validData = data else { + let failureReason = "String could not be serialized. Input data was nil." + let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + if let encodingName = response?.textEncodingName where encoding == nil { + encoding = CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName) + ) + } + + let actualEncoding = encoding ?? NSISOLatin1StringEncoding + + if let string = String(data: validData, encoding: actualEncoding) { + return .Success(string) + } else { + let failureReason = "String could not be serialized with encoding: \(actualEncoding)" + let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + server response, falling back to the default HTTP default character set, + ISO-8859-1. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseString( + encoding encoding: NSStringEncoding? = nil, + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + + /** + Creates a response serializer that returns a JSON object constructed from the response data using + `NSJSONSerialization` with the specified reading options. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + + - returns: A JSON object response serializer. + */ + public static func JSONResponseSerializer( + options options: NSJSONReadingOptions = .AllowFragments) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "JSON could not be serialized. Input data was nil or zero length." + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) + return .Success(JSON) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseJSON( + options options: NSJSONReadingOptions = .AllowFragments, + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.JSONResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + + /** + Creates a response serializer that returns an object constructed from the response data using + `NSPropertyListSerialization` with the specified reading options. + + - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. + + - returns: A property list object response serializer. + */ + public static func propertyListResponseSerializer( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "Property list could not be serialized. Input data was nil or zero length." + let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) + return .Success(plist) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The property list reading options. `0` by default. + - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 + arguments: the URL request, the URL response, the server data and the result + produced while creating the property list. + + - returns: The request. + */ + public func responsePropertyList( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 00000000000..a8557cabb42 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,101 @@ +// Result.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Used to represent whether a request was successful or encountered an error. + + - Success: The request and all post processing operations were successful resulting in the serialization of the + provided associated value. + - Failure: The request encountered an error resulting in a failure. The associated values are the original data + provided by the server as well as the error that caused the failure. +*/ +public enum Result { + case Success(Value) + case Failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .Success: + return true + case .Failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .Success(let value): + return value + case .Failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .Success: + return nil + case .Failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .Success: + return "SUCCESS" + case .Failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .Success(let value): + return "SUCCESS: \(value)" + case .Failure(let error): + return "FAILURE: \(error)" + } + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 00000000000..07cd848a606 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,302 @@ +// ServerTrustPolicy.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +public class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /** + Initializes the `ServerTrustPolicyManager` instance with the given policies. + + Since different servers and web services can have different leaf certificates, intermediate and even root + certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + pinning for host3 and disabling evaluation for host4. + + - parameter policies: A dictionary of all policies mapped to a particular host. + + - returns: The new `ServerTrustPolicyManager` instance. + */ + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /** + Returns the `ServerTrustPolicy` for the given host if applicable. + + By default, this method will return the policy that perfectly matches the given host. Subclasses could override + this method and implement more complex mapping implementations such as wildcards. + + - parameter host: The host to use when searching for a matching policy. + + - returns: The server trust policy for the given host if found. + */ + public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension NSURLSession { + private struct AssociatedKeys { + static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/** + The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when + connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust + with a given set of criteria to determine whether the server trust is valid and the connection should be made. + + Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other + vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged + to route all communication over an HTTPS connection with pinning enabled. + + - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to + validate the host provided by the challenge. Applications are encouraged to always + validate the host in production environments to guarantee the validity of the server's + certificate chain. + + - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is + considered valid if one of the pinned certificates match one of the server certificates. + By validating both the certificate chain and host, certificate pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered + valid if one of the pinned public keys match one of the server certificate public keys. + By validating both the certificate chain and host, public key pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. + + - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. +*/ +public enum ServerTrustPolicy { + case PerformDefaultEvaluation(validateHost: Bool) + case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case DisableEvaluation + case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) + + // MARK: - Bundle Location + + /** + Returns all certificates within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `.cer` files. + + - returns: All certificates within the given bundle. + */ + public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) + }.flatten()) + + for path in paths { + if let + certificateData = NSData(contentsOfFile: path), + certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /** + Returns all public keys within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `*.cer` files. + + - returns: All public keys within the given bundle. + */ + public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificatesInBundle(bundle) { + if let publicKey = publicKeyForCertificate(certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /** + Evaluates whether the server trust is valid for the given host. + + - parameter serverTrust: The server trust to evaluate. + - parameter host: The host of the challenge protection space. + + - returns: Whether the server trust is valid. + */ + public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .PerformDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateDataForTrust(serverTrust) + let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData.isEqualToData(pinnedCertificateData) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .DisableEvaluation: + serverTrustIsValid = true + case let .CustomEvaluation(closure): + serverTrustIsValid = closure(serverTrust: serverTrust, host: host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType(kSecTrustResultInvalid) + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType(kSecTrustResultUnspecified) + let proceed = SecTrustResultType(kSecTrustResultProceed) + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateDataForTrust(trust: SecTrust) -> [NSData] { + var certificates: [SecCertificate] = [] + + for index in 0.. [NSData] { + return certificates.map { SecCertificateCopyData($0) as NSData } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust where trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift new file mode 100644 index 00000000000..bc9ee450c5a --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -0,0 +1,180 @@ +// Stream.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if !os(watchOS) + +@available(iOS 9.0, OSX 10.11, *) +extension Manager { + private enum Streamable { + case Stream(String, Int) + case NetService(NSNetService) + } + + private func stream(streamable: Streamable) -> Request { + var streamTask: NSURLSessionStreamTask! + + switch streamable { + case .Stream(let hostName, let port): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithHostName(hostName, port: port) + } + case .NetService(let netService): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithNetService(netService) + } + } + + let request = Request(session: session, task: streamTask) + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + /** + Creates a request for bidirectional streaming with the given hostname and port. + + - parameter hostName: The hostname of the server to connect to. + - parameter port: The port of the server to connect to. + + :returns: The created stream request. + */ + public func stream(hostName hostName: String, port: Int) -> Request { + return stream(.Stream(hostName, port)) + } + + /** + Creates a request for bidirectional streaming with the given `NSNetService`. + + - parameter netService: The net service used to identify the endpoint. + + - returns: The created stream request. + */ + public func stream(netService netService: NSNetService) -> Request { + return stream(.NetService(netService)) + } +} + +// MARK: - + +@available(iOS 9.0, OSX 10.11, *) +extension Manager.SessionDelegate: NSURLSessionStreamDelegate { + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. + public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. + public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. + public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. + public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + // MARK: Delegate Methods + + /** + Tells the delegate that the read side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /** + Tells the delegate that the write side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /** + Tells the delegate that the system has determined that a better route to the host is available. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /** + Tells the delegate that the stream task has been completed and provides the unopened stream objects. + + - parameter session: The session. + - parameter streamTask: The stream task. + - parameter inputStream: The new input stream. + - parameter outputStream: The new output stream. + */ + public func URLSession( + session: NSURLSession, + streamTask: NSURLSessionStreamTask, + didBecomeInputStream inputStream: NSInputStream, + outputStream: NSOutputStream) + { + streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift new file mode 100644 index 00000000000..ee6b34ced5b --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -0,0 +1,372 @@ +// Upload.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Manager { + private enum Uploadable { + case Data(NSURLRequest, NSData) + case File(NSURLRequest, NSURL) + case Stream(NSURLRequest, NSInputStream) + } + + private func upload(uploadable: Uploadable) -> Request { + var uploadTask: NSURLSessionUploadTask! + var HTTPBodyStream: NSInputStream? + + switch uploadable { + case .Data(let request, let data): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) + } + case .File(let request, let fileURL): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) + } + case .Stream(let request, let stream): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithStreamedRequest(request) + } + + HTTPBodyStream = stream + } + + let request = Request(session: session, task: uploadTask) + + if HTTPBodyStream != nil { + request.delegate.taskNeedNewBodyStream = { _, _ in + return HTTPBodyStream + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: File + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return upload(.File(URLRequest.URLRequest, file)) + } + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + return upload(mutableURLRequest, file: file) + } + + // MARK: Data + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return upload(.Data(URLRequest.URLRequest, data)) + } + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, data: data) + } + + // MARK: Stream + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return upload(.Stream(URLRequest.URLRequest, stream)) + } + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, stream: stream) + } + + // MARK: MultipartFormData + + /// Default memory threshold used when encoding `MultipartFormData`. + public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 + + /** + Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + associated values. + + - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with + streaming information. + - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + error. + */ + public enum MultipartFormDataEncodingResult { + case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) + case Failure(ErrorType) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload( + mutableURLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + let formData = MultipartFormData() + multipartFormData(formData) + + let URLRequestWithContentType = URLRequest.URLRequest + URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + do { + let data = try formData.encode() + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, data: data), + streamingFromDisk: false, + streamFileURL: nil + ) + + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } else { + let fileManager = NSFileManager.defaultManager() + let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") + let fileName = NSUUID().UUIDString + let fileURL = directoryURL.URLByAppendingPathComponent(fileName) + + do { + try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) + try formData.writeEncodedDataToDisk(fileURL) + + dispatch_async(dispatch_get_main_queue()) { + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, file: fileURL), + streamingFromDisk: true, + streamFileURL: fileURL + ) + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } + } + } +} + +// MARK: - + +extension Request { + + // MARK: - UploadTaskDelegate + + class UploadTaskDelegate: DataTaskDelegate { + var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } + var uploadProgress: ((Int64, Int64, Int64) -> Void)! + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + progress.totalUnitCount = totalBytesExpectedToSend + progress.completedUnitCount = totalBytesSent + + uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + } + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 00000000000..71d21e1afa6 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,189 @@ +// Validation.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Request { + + /** + Used to represent whether validation was successful or encountered an error resulting in a failure. + + - Success: The validation was successful. + - Failure: The validation failed encountering the provided error. + */ + public enum ValidationResult { + case Success + case Failure(NSError) + } + + /** + A closure used to validate a request that takes a URL request and URL response, and returns whether the + request was valid. + */ + public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult + + /** + Validates the request, using the specified closure. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter validation: A closure to validate the request. + + - returns: The request. + */ + public func validate(validation: Validation) -> Self { + delegate.queue.addOperationWithBlock { + if let + response = self.response where self.delegate.error == nil, + case let .Failure(error) = validation(self.request, response) + { + self.delegate.error = error + } + } + + return self + } + + // MARK: - Status Code + + /** + Validates that the response has a status code in the specified range. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter range: The range of acceptable status codes. + + - returns: The request. + */ + public func validate(statusCode acceptableStatusCode: S) -> Self { + return validate { _, response in + if acceptableStatusCode.contains(response.statusCode) { + return .Success + } else { + let failureReason = "Response status code was unacceptable: \(response.statusCode)" + return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + } + } + } + + // MARK: - Content-Type + + private struct MIMEType { + let type: String + let subtype: String + + init?(_ string: String) { + let components: [String] = { + let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) + let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) + return split.componentsSeparatedByString("/") + }() + + if let + type = components.first, + subtype = components.last + { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(MIME: MIMEType) -> Bool { + switch (type, subtype) { + case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + /** + Validates that the response has a content type in the specified array. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + + - returns: The request. + */ + public func validate(contentType acceptableContentTypes: S) -> Self { + return validate { _, response in + guard let validData = self.delegate.data where validData.length > 0 else { return .Success } + + if let + responseContentType = response.MIMEType, + responseMIMEType = MIMEType(responseContentType) + { + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { + return .Success + } + } + } else { + for contentType in acceptableContentTypes { + if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { + return .Success + } + } + } + + let failureReason: String + + if let responseContentType = response.MIMEType { + failureReason = ( + "Response content type \"\(responseContentType)\" does not match any acceptable " + + "content types: \(acceptableContentTypes)" + ) + } else { + failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" + } + + return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + } + } + + // MARK: - Automatic + + /** + Validates that the response has a status code in the default acceptable range of 200...299, and that the content + type matches any specified in the Accept HTTP header field. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - returns: The request. + */ + public func validate() -> Self { + let acceptableStatusCodes: Range = 200..<300 + let acceptableContentTypes: [String] = { + if let accept = request?.valueForHTTPHeaderField("Accept") { + return accept.componentsSeparatedByString(",") + } + + return ["*/*"] + }() + + return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 00000000000..99bf5ef601f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "8.0", + "osx": "10.9" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "license": "Apache License, Version 2.0", + "authors": "Apache License, Version 2.0", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "PromiseKit": [ + "~> 3.1.1" + ], + "Alamofire": [ + "~> 3.1.5" + ] + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 00000000000..fa9ebeb16ef --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,41 @@ +PODS: + - Alamofire (3.1.5) + - OMGHTTPURLRQ (3.1.2): + - OMGHTTPURLRQ/RQ (= 3.1.2) + - OMGHTTPURLRQ/FormURLEncode (3.1.2) + - OMGHTTPURLRQ/RQ (3.1.2): + - OMGHTTPURLRQ/FormURLEncode + - OMGHTTPURLRQ/UserAgent + - OMGHTTPURLRQ/UserAgent (3.1.2) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.1.5) + - PromiseKit (~> 3.1.1) + - PromiseKit (3.1.1): + - PromiseKit/Foundation (= 3.1.1) + - PromiseKit/QuartzCore (= 3.1.1) + - PromiseKit/UIKit (= 3.1.1) + - PromiseKit/CorePromise (3.1.1) + - PromiseKit/Foundation (3.1.1): + - OMGHTTPURLRQ (~> 3.1.0) + - PromiseKit/CorePromise + - PromiseKit/QuartzCore (3.1.1): + - PromiseKit/CorePromise + - PromiseKit/UIKit (3.1.1): + - PromiseKit/CorePromise + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 + OMGHTTPURLRQ: 38316b56d88125c600bcdb16df8329147da2b0ee + PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace + PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb + +PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 + +COCOAPODS: 1.0.0 diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown similarity index 97% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown index ff905517872..1cd71258ad3 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown @@ -39,7 +39,7 @@ NSData *data2 = UIImagePNGRepresentation(image2); [multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"]; // SUPER Ideally you would not want to re-encode the JPEG as the process -// is lossy. If you image comes from the AssetLibrary you *CAN* get the +// is lossy. If your image comes from the AssetLibrary you *CAN* get the // original `NSData`. See stackoverflow.com. UIImage *image3 = [UIImage imageNamed:@"image3"]; NSData *data3 = UIImageJPEGRepresentation(image3); @@ -97,7 +97,7 @@ your API keys that registering at https://dev.twitter.com will provide you. ```objc -NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com"consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; +NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; [rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"]; [NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { @@ -142,4 +142,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` \ No newline at end of file +``` diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m similarity index 97% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m index 0854acd0eb7..3f48ace500e 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m @@ -71,8 +71,8 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() { @implementation OMGHTTPURLRQ + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { - id queryString = OMGFormURLEncode(params); - if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; + NSString *queryString = OMGFormURLEncode(params); + if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; id url = [NSURL URLWithString:urlString]; if (!url) { diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj similarity index 79% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index da35c633e44..b435c9a1477 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -10,26 +10,27 @@ 01BD61BBC475EB3369237B84FE24D3EE /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 0268F9278E32ACC1F996F4E2E45622B5 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */; }; + 066335E8B1AEEB4CF633B2ED738D6223 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */; }; 06F7C0C55DF4C09C015159F6B0802EB1 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84319E048FE6DD89B905FA3A81005C5F /* join.swift */; }; 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; 0BDA43D8F48C8B0D504C440046FAF681 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 0D240D796AAD10F0119A1D7AC2570AAA /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */; }; 11C221075C5B20BDEEB3DDF8EAC99E63 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */; }; 11EA8D6B0352FD31F520F983CFB9D993 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */; }; 12348513CB81BD05B497C210905CDF65 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 124EFF5E3C46EC88F47C52479FA6ACAF /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */; }; - 1287903F965945AEB5EFC4EE768C7B38 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */; }; 15ECEBA1EFBD023AEA47F36524270D2C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; 18FAC6B4FD3B44CB353C7A6027286100 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1AC7E88F0EC64D1D4E83CE7767BFD2B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */; }; + 1CB5E10963E95432A9674D1FF2B48FA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; 1CDA074C6DC95876D85E13ECF882B93A /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; 1E1010EA437F154A554D04F7F3A894EC /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */; }; 25FBB92AFB8F5A777CE8E40EC3B9DACA /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; 2B38BB4603B4286FF8D7A780372E947F /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2D9379807BA243E1CE457D1BE963DA09 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; - 35F6B35131F89EA23246C6508199FB05 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; 3860D960E37C1257BDA54626CA592E86 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 387C7387FDC662D23D743879B6143D59 /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */; }; 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -40,7 +41,6 @@ 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */; }; 516D41E4D035A817CC5116C11302E408 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 523C1819FC864864A9715CF713DD12E9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5D7EAE5725A7E750B51FD27AECB5F0FD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AD59903FAA8315AD0036AC459FFB97F /* join.m */; }; 5EE5E1CA27F3CB04A5DCF5BB90B76000 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; @@ -50,28 +50,32 @@ 6A128FE350973D8A693E3F063C5E4A49 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */; }; 6B0A17CD24331793D2504E0FBBAF5EB2 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 6D264CCBD7DAC0A530076FB1A847EEC7 /* Pods-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */; }; 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 73FA79FDB37E5C458B996012BFB0CF04 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */; }; 7D7A40DBAC93241786E8C553921E8C86 /* OMGHTTPURLRQ.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */; }; 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */; }; 81A2DB65C0742D785DE7C2609CC14140 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */; }; + 825D1C93689636D09044C5077E5D905F /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */; }; 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */; }; 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */; }; 857E5961D9F6E23BD86DEB613A1499C7 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; 88B3F911629C08DEEB226F3B294AAB36 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */; }; + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8C4A96A3E69C772990E3E922D0FD1BC4 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8D3A68D3CBD8A1D89099F704A04A04FC /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */; }; 8E3861989641484EE3095722EC08B5A9 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */; }; 909B0A29022956D90C32C4AA319F75D1 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */; }; - 96D99D0C2472535A169DED65CB231CD7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; 97D71F12142A541BEEF425805D51379E /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */; }; + 9876AE0817723FB5E93A94B1E1906901 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; 9CFBA896DF45B68C788F80013AC3FDBB /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */; }; A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */; }; A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = A04177B09D9596450D827FE49A36C4C4 /* Download.swift */; }; + A4BA36ADDDFBCF208CC58E552C0AC85C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; ADEEE5F368B5D707D03E78FD75C59048 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */; }; B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */; }; B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */; }; + C141DD535C090B58DD95D53988AAA42B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */; }; C86881D2285095255829A578F0A85300 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = B868468092D7B2489B889A50981C9247 /* after.m */; }; C86CE0A47FAD4C9B2929A335D62A179E /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */; }; @@ -81,22 +85,20 @@ CE225CF07E6E385F014883D607AFA44D /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */; }; CE89E5C528D52BBCBCD23309603BA6D1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; D1735D6C4D574339EB49024228448459 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */; }; - D1E8B31EFCBDE00F108E739AD69425C0 /* Pods-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */; }; D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */; }; D546A4DBA3F7750F45A6F63B994C081C /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */; }; D93596046CD3B301F4EC99A7A118C82C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */; }; + D97B0097ACB39F4E308E996F4F2AC836 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; DBD1F4247E1C591AE4EE5531599AB170 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - DD8D067A7F742F39B87FA04CE12DD118 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; E2B0094FAAEA55C55AD141136F650E35 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; EA35E77B4F31DC3E1D224458E0BC959D /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; EA67B414E392EFD2B14742F55A595596 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */; }; - EA691570F0F8066651EE2A7066426384 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */; }; EB3C88CDAF122BA763FEF85758370C7C /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */; }; EB9A1F33DB49ADA09F6E7F19A2C30357 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */; }; ED30A8B82BA1D53CBC370B1DC18DA1EB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16730DAF3E51C161D8247E473F069E71 /* when.swift */; }; - EEF6E654182421FEBC0CC202E72F71A8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; F4582E8DC1C9F362ADA4BAE9CEF8B681 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */; }; F700EAA9F9F6C1F99C83B45D05C5AD14 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; F7161E50F083B2267363F243C4E4B78F /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */; }; @@ -104,16 +106,10 @@ FB0B33F03AC2BC8A7FC7FD912C12CC22 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */; }; FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */; }; FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */; }; + FFA95B8BEE43D793FF453E49099AC52E /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0B92202857E3535647B0785253083518 /* QuartzCore.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 014385BD85FA83B60A03ADE9E8844F33 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 2FD913B4E24277823983BABFDB071664; - remoteInfo = PetstoreClient; - }; 4BED27A854EA6600536518D29BBB3670 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; @@ -121,12 +117,19 @@ remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; remoteInfo = Alamofire; }; - 769630CDAAA8C24AA5B4C81A85C45AC8 /* PBXContainerItemProxy */ = { + 6795BDA8BF074DFC4E5D1758C8F88C2A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; - remoteInfo = Alamofire; + remoteGlobalIDString = 2FD913B4E24277823983BABFDB071664; + remoteInfo = PetstoreClient; + }; + 7DE91DDF2036FF7431AF3F0DAD4A9C87 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 25EDA9CFC641C69402B3857A2C4A39F0; + remoteInfo = PromiseKit; }; 8059767A82D94C9F7F7C16D030819C4E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; @@ -135,20 +138,20 @@ remoteGlobalIDString = 190ACD3A51BC90B85EADB13E9CDD207B; remoteInfo = OMGHTTPURLRQ; }; - 9AD20158D23CE70A2A91E5B7859090C3 /* PBXContainerItemProxy */ = { + 8E08EC4F5A85093B738D80C4F04BA3F1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteInfo = Alamofire; + }; + ABF692D458113B268763EDC4670EAF7A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 190ACD3A51BC90B85EADB13E9CDD207B; remoteInfo = OMGHTTPURLRQ; }; - B5FB8931CDF8801206EDD2FEF94793BF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 25EDA9CFC641C69402B3857A2C4A39F0; - remoteInfo = PromiseKit; - }; ECAC5E4454026C822004659466983ADD /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; @@ -159,11 +162,15 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+Cancellation.h"; path = "Sources/NSError+Cancellation.h"; sourceTree = ""; }; 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Categories/QuartzCore/CALayer+AnyPromise.m"; sourceTree = ""; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; + 0B92202857E3535647B0785253083518 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; + 0C552CDBDD89D489D23D5D4E28356F84 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; @@ -183,19 +190,24 @@ 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Categories/QuartzCore/CALayer+AnyPromise.h"; sourceTree = ""; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; - 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-umbrella.h"; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Categories/UIKit/UIView+AnyPromise.m"; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = dispatch_promise.swift; path = Sources/dispatch_promise.swift; sourceTree = ""; }; 3950B63B8EB1B9CD8FC31CDA8CC2E7C7 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; 3CE589B7B1FE57084403D25DC49528B5 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.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 = ""; }; 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; @@ -203,24 +215,25 @@ 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Categories/Foundation/NSURLSession+Promise.swift"; sourceTree = ""; }; 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; - 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - 5CA1C154DFC54DFFB12A754B9A0BBDFC /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActionSheet+AnyPromise.h"; path = "Categories/UIKit/UIActionSheet+AnyPromise.h"; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; 6AD59903FAA8315AD0036AC459FFB97F /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 79A9DEDC89FE8336BF5FEDAAF75BF7FC /* Pods.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Pods.modulemap; sourceTree = ""; }; + 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; 84319E048FE6DD89B905FA3A81005C5F /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 87B213035BAC5F75386F62D3C75D2342 /* Pods-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-acknowledgements.plist"; sourceTree = ""; }; 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; - 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-dummy.m"; sourceTree = ""; }; 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; @@ -229,8 +242,10 @@ 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; 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 = ""; }; 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; - 977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.debug.xcconfig; sourceTree = ""; }; + 97FF5C0140A433518CF653B6A520F27A /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; @@ -245,51 +260,58 @@ B868468092D7B2489B889A50981C9247 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Categories/Foundation/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; B9E21DC1171D712B2D2307EE5034D99E /* OMGHTTPURLRQ-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-prefix.pch"; sourceTree = ""; }; - BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Categories/Foundation/afterlife.swift; sourceTree = ""; }; C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Categories/UIKit/PMKAlertController.swift; sourceTree = ""; }; CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; - CBC0F7C552B739C909B650A0F42F7F38 /* Pods-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-resources.sh"; sourceTree = ""; }; CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; - D0405803033A2A777B8E4DFA0C1800ED /* Pods-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-acknowledgements.markdown"; sourceTree = ""; }; + CF8754792D6C49D6F5C8859350F48B35 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; - D4248CF20178C57CEFEFAAF453C0DC75 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Categories/UIKit/UIViewController+Promise.swift"; sourceTree = ""; }; D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Categories/Foundation/NSObject+Promise.swift"; sourceTree = ""; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; - D931A99C6B5A8E0F69C818C6ECC3C44F /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.release.xcconfig; sourceTree = ""; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGUserAgent.m; path = Sources/OMGUserAgent.m; sourceTree = ""; }; - E160B50E4D11692AA38E74C897D69C61 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Categories/UIKit/UIView+Promise.swift"; sourceTree = ""; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Sources/URLDataPromise.swift; sourceTree = ""; }; - E7F21354943D9F42A70697D5A5EF72E9 /* Pods-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-frameworks.sh"; sourceTree = ""; }; - E8446514FBAD26C0E18F24A5715AEF67 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - EBC4140FCBB5B4D3A955B1608C165C04 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AnyPromise.m"; path = "Categories/UIKit/UIAlertView+AnyPromise.m"; sourceTree = ""; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-umbrella.h"; sourceTree = ""; }; - FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActionSheet+Promise.swift"; path = "Categories/UIKit/UIActionSheet+Promise.swift"; sourceTree = ""; }; + FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 74904C0940192CCB30B90142B3348507 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1CB5E10963E95432A9674D1FF2B48FA1 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 9792A6BDBB07FB15453527B4370E3086 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 35F6B35131F89EA23246C6508199FB05 /* Foundation.framework in Frameworks */, + C141DD535C090B58DD95D53988AAA42B /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -297,7 +319,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 96D99D0C2472535A169DED65CB231CD7 /* Foundation.framework in Frameworks */, + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -305,18 +327,10 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - EEF6E654182421FEBC0CC202E72F71A8 /* Foundation.framework in Frameworks */, + 066335E8B1AEEB4CF633B2ED738D6223 /* Foundation.framework in Frameworks */, 7D7A40DBAC93241786E8C553921E8C86 /* OMGHTTPURLRQ.framework in Frameworks */, - 1287903F965945AEB5EFC4EE768C7B38 /* QuartzCore.framework in Frameworks */, - EA691570F0F8066651EE2A7066426384 /* UIKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - FA26D2C7E461A1BBD50054579AFE2F7C /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - DD8D067A7F742F39B87FA04CE12DD118 /* Foundation.framework in Frameworks */, + FFA95B8BEE43D793FF453E49099AC52E /* QuartzCore.framework in Frameworks */, + 825D1C93689636D09044C5077E5D905F /* UIKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -325,14 +339,35 @@ buildActionMask = 2147483647; files = ( 9CFBA896DF45B68C788F80013AC3FDBB /* Alamofire.framework in Frameworks */, - 523C1819FC864864A9715CF713DD12E9 /* Foundation.framework in Frameworks */, + A4BA36ADDDFBCF208CC58E552C0AC85C /* Foundation.framework in Frameworks */, FB0B33F03AC2BC8A7FC7FD912C12CC22 /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 01A9CB10E1E9A90B6A796034AF093E8C /* Products */ = { + isa = PBXGroup; + children = ( + F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */, + 97FF5C0140A433518CF653B6A520F27A /* OMGHTTPURLRQ.framework */, + FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */, + CF8754792D6C49D6F5C8859350F48B35 /* Pods_SwaggerClient.framework */, + FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */, + 0C552CDBDD89D489D23D5D4E28356F84 /* PromiseKit.framework */, + ); + name = Products; + sourceTree = ""; + }; 07467E828160702D1DB7EC2F492C337C /* UserAgent */ = { isa = PBXGroup; children = ( @@ -376,24 +411,6 @@ name = "Development Pods"; sourceTree = ""; }; - 75D98FF52E597A11900E131B6C4E1ADA /* Pods */ = { - isa = PBXGroup; - children = ( - E8446514FBAD26C0E18F24A5715AEF67 /* Info.plist */, - 79A9DEDC89FE8336BF5FEDAAF75BF7FC /* Pods.modulemap */, - D0405803033A2A777B8E4DFA0C1800ED /* Pods-acknowledgements.markdown */, - 87B213035BAC5F75386F62D3C75D2342 /* Pods-acknowledgements.plist */, - 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */, - E7F21354943D9F42A70697D5A5EF72E9 /* Pods-frameworks.sh */, - CBC0F7C552B739C909B650A0F42F7F38 /* Pods-resources.sh */, - 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */, - 977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */, - DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */, - ); - name = Pods; - path = "Target Support Files/Pods"; - sourceTree = ""; - }; 76DC20E0A9F8CDC0E47176B58A9C5BD5 /* Foundation */ = { isa = PBXGroup; children = ( @@ -413,12 +430,12 @@ 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( - BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */, + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */, - D6592B983C64CE2427DF9CF38F4BD1C1 /* Products */, - B7B80995527643776607AFFA75B91E24 /* Targets Support Files */, + 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); sourceTree = ""; }; @@ -455,6 +472,24 @@ name = QuartzCore; 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 = ""; + }; 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */ = { isa = PBXGroup; children = ( @@ -551,12 +586,14 @@ path = Classes; sourceTree = ""; }; - B7B80995527643776607AFFA75B91E24 /* Targets Support Files */ = { + B4A5C9FBC309EB945E2E089539878931 /* iOS */ = { isa = PBXGroup; children = ( - 75D98FF52E597A11900E131B6C4E1ADA /* Pods */, + 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */, + 0B92202857E3535647B0785253083518 /* QuartzCore.framework */, + 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */, ); - name = "Targets Support Files"; + name = iOS; sourceTree = ""; }; BEACE1971060500B96701CBC3F667BAE /* CorePromise */ = { @@ -587,6 +624,15 @@ name = CorePromise; sourceTree = ""; }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */ = { isa = PBXGroup; children = ( @@ -597,16 +643,22 @@ name = Pods; sourceTree = ""; }; - D6592B983C64CE2427DF9CF38F4BD1C1 /* Products */ = { + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { isa = PBXGroup; children = ( - EBC4140FCBB5B4D3A955B1608C165C04 /* Alamofire.framework */, - 5CA1C154DFC54DFFB12A754B9A0BBDFC /* OMGHTTPURLRQ.framework */, - E160B50E4D11692AA38E74C897D69C61 /* PetstoreClient.framework */, - D931A99C6B5A8E0F69C818C6ECC3C44F /* Pods.framework */, - D4248CF20178C57CEFEFAAF453C0DC75 /* PromiseKit.framework */, + 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 */, ); - name = Products; + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; sourceTree = ""; }; D9FC474F1DB94FC75B3AAC120F0D4AB7 /* PromiseKit */ = { @@ -635,21 +687,11 @@ A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */, 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */, A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */, - E8D8DAC96ED2B9203F380FB45F6DBE39 /* iOS */, + B4A5C9FBC309EB945E2E089539878931 /* iOS */, ); name = Frameworks; sourceTree = ""; }; - E8D8DAC96ED2B9203F380FB45F6DBE39 /* iOS */ = { - isa = PBXGroup; - children = ( - FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */, - FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */, - 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */, - ); - name = iOS; - sourceTree = ""; - }; E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { isa = PBXGroup; children = ( @@ -713,6 +755,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 4EC64FD39389DAFE4AD4266FC3328DFF /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D97B0097ACB39F4E308E996F4F2AC836 /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -721,14 +771,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 7E1332ABD911123D7A873D6D87E2F182 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - D1E8B31EFCBDE00F108E739AD69425C0 /* Pods-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 8EC2461DE4442A7991319873E6012164 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -740,6 +782,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ @@ -757,7 +807,28 @@ ); name = OMGHTTPURLRQ; productName = OMGHTTPURLRQ; - productReference = 5CA1C154DFC54DFFB12A754B9A0BBDFC /* OMGHTTPURLRQ.framework */; + productReference = 97FF5C0140A433518CF653B6A520F27A /* OMGHTTPURLRQ.framework */; + productType = "com.apple.product-type.framework"; + }; + 1EABA30CF432461C9C71EFB7319C5EC0 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = C9F2C0984774847F556FBA38A5DFA380 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + 17C136CACEBA2BEF9A840E699AB10D69 /* Sources */, + 74904C0940192CCB30B90142B3348507 /* Frameworks */, + 4EC64FD39389DAFE4AD4266FC3328DFF /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + FFAF754843564CB3D6F424CE47B71A27 /* PBXTargetDependency */, + 679C1EDCB1F411D8FFB2673C78614B15 /* PBXTargetDependency */, + 08587102FAC1423B332ADA2E2AD0BC0A /* PBXTargetDependency */, + 66E283C897B0821EC278FCF08B47AD54 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = CF8754792D6C49D6F5C8859350F48B35 /* Pods_SwaggerClient.framework */; productType = "com.apple.product-type.framework"; }; 25EDA9CFC641C69402B3857A2C4A39F0 /* PromiseKit */ = { @@ -775,7 +846,7 @@ ); name = PromiseKit; productName = PromiseKit; - productReference = D4248CF20178C57CEFEFAAF453C0DC75 /* PromiseKit.framework */; + productReference = 0C552CDBDD89D489D23D5D4E28356F84 /* PromiseKit.framework */; productType = "com.apple.product-type.framework"; }; 2FD913B4E24277823983BABFDB071664 /* PetstoreClient */ = { @@ -794,7 +865,7 @@ ); name = PetstoreClient; productName = PetstoreClient; - productReference = E160B50E4D11692AA38E74C897D69C61 /* PetstoreClient.framework */; + productReference = FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { @@ -811,28 +882,24 @@ ); name = Alamofire; productName = Alamofire; - productReference = EBC4140FCBB5B4D3A955B1608C165C04 /* Alamofire.framework */; + productReference = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; - 7A5DBD588D2CC1C0CB1C42D4ED613FE4 /* Pods */ = { + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 8CB3C5DF3F4B6413A6F2D003B58CCF32 /* Build configuration list for PBXNativeTarget "Pods" */; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; buildPhases = ( - 91F4D6732A1613C9660866E34445A67B /* Sources */, - FA26D2C7E461A1BBD50054579AFE2F7C /* Frameworks */, - 7E1332ABD911123D7A873D6D87E2F182 /* Headers */, + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, ); buildRules = ( ); dependencies = ( - 64142DAEC5D96F7E876BBE00917C0E9D /* PBXTargetDependency */, - F74DEE1C89F05CC835997330B0E3B7C1 /* PBXTargetDependency */, - 2673248EF608AB8375FABCFDA8141072 /* PBXTargetDependency */, - 5433AD51A3DC696530C96B8A7D78ED7D /* PBXTargetDependency */, ); - name = Pods; - productName = Pods; - productReference = D931A99C6B5A8E0F69C818C6ECC3C44F /* Pods.framework */; + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -841,7 +908,7 @@ D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0700; + LastSwiftUpdateCheck = 0730; LastUpgradeCheck = 0700; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; @@ -852,20 +919,29 @@ en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; - productRefGroup = D6592B983C64CE2427DF9CF38F4BD1C1 /* Products */; + productRefGroup = 01A9CB10E1E9A90B6A796034AF093E8C /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */, 2FD913B4E24277823983BABFDB071664 /* PetstoreClient */, - 7A5DBD588D2CC1C0CB1C42D4ED613FE4 /* Pods */, + 1EABA30CF432461C9C71EFB7319C5EC0 /* Pods-SwaggerClient */, + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, 25EDA9CFC641C69402B3857A2C4A39F0 /* PromiseKit */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ + 0529825EC79AED06C77091DC0F061854 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 0DDA01F58E1381BEA0D7FB759B75A456 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -929,6 +1005,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 17C136CACEBA2BEF9A840E699AB10D69 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9876AE0817723FB5E93A94B1E1906901 /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 44321F32F148EB47FF23494889576DF5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -940,14 +1024,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 91F4D6732A1613C9660866E34445A67B /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 6D264CCBD7DAC0A530076FB1A847EEC7 /* Pods-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -973,23 +1049,23 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 2673248EF608AB8375FABCFDA8141072 /* PBXTargetDependency */ = { + 08587102FAC1423B332ADA2E2AD0BC0A /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PetstoreClient; target = 2FD913B4E24277823983BABFDB071664 /* PetstoreClient */; - targetProxy = 014385BD85FA83B60A03ADE9E8844F33 /* PBXContainerItemProxy */; + targetProxy = 6795BDA8BF074DFC4E5D1758C8F88C2A /* PBXContainerItemProxy */; }; - 5433AD51A3DC696530C96B8A7D78ED7D /* PBXTargetDependency */ = { + 66E283C897B0821EC278FCF08B47AD54 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; target = 25EDA9CFC641C69402B3857A2C4A39F0 /* PromiseKit */; - targetProxy = B5FB8931CDF8801206EDD2FEF94793BF /* PBXContainerItemProxy */; + targetProxy = 7DE91DDF2036FF7431AF3F0DAD4A9C87 /* PBXContainerItemProxy */; }; - 64142DAEC5D96F7E876BBE00917C0E9D /* PBXTargetDependency */ = { + 679C1EDCB1F411D8FFB2673C78614B15 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; - targetProxy = 769630CDAAA8C24AA5B4C81A85C45AC8 /* PBXContainerItemProxy */; + name = OMGHTTPURLRQ; + target = 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */; + targetProxy = ABF692D458113B268763EDC4670EAF7A /* PBXContainerItemProxy */; }; C893B48B47F4A7541102DAAFECFC50F2 /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -997,12 +1073,6 @@ target = 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */; targetProxy = 8059767A82D94C9F7F7C16D030819C4E /* PBXContainerItemProxy */; }; - F74DEE1C89F05CC835997330B0E3B7C1 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = OMGHTTPURLRQ; - target = 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */; - targetProxy = 9AD20158D23CE70A2A91E5B7859090C3 /* PBXContainerItemProxy */; - }; FAC5685F6C40E5D74404831646CBC453 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; @@ -1015,28 +1085,40 @@ target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; targetProxy = 4BED27A854EA6600536518D29BBB3670 /* PBXContainerItemProxy */; }; + FFAF754843564CB3D6F424CE47B71A27 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + targetProxy = 8E08EC4F5A85093B738D80C4F04BA3F1 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 0D12EBEB35AC8FA740B275C8105F9152 /* Release */ = { + 13D83F6E46BF53D2E6C3EB7C33E93BBF /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 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_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + 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"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1045,22 +1127,116 @@ }; name = Release; }; - 10966F49AC953FB6BFDCBF072AF5B251 /* Release */ = { + 237DD903E4E61B0FFB3BB69F98EE1A1A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 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"; 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/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6D58F928D13C57FA81A386B6364889AA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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 = NO; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 83EBAB51C518173D901D2A7FE10401AC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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/PetstoreClient/PetstoreClient.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = PetstoreClient; @@ -1072,151 +1248,11 @@ }; name = Release; }; - 1361791756A3908370041AE99E5CF772 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - INFOPLIST_FILE = "Target Support Files/Pods/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/Pods.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_NAME = Pods; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 28973E73A6075E48EBE277098505D118 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = 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 = 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 = YES; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 4D5CD4E08FD8D405881C59A5535E6CE8 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_PREFIX_HEADER = "Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/OMGHTTPURLRQ/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = OMGHTTPURLRQ; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 7B7ACBE5930AD378A2346DC89BAD1027 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - 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.2; - 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; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 819D3D3D508154D9CFF3CE30C13E000E /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_PREFIX_HEADER = "Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/OMGHTTPURLRQ/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = OMGHTTPURLRQ; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 8D1534490D941DCA47C62AC4314182AF /* Debug */ = { + 84FD87D359382A37B07149A12641B965 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -1231,10 +1267,12 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 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)", ); @@ -1252,25 +1290,89 @@ }; name = Debug; }; - 94652EA7B5323CE393BCE396E7262170 /* Debug */ = { + 9B26D3A39011247999C097562A550399 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 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_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + 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; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A1075551063662DDB4B1D70BD9D48C6E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/OMGHTTPURLRQ/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/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = OMGHTTPURLRQ; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AEB3F05CF4CA7390DB94997A30E330AD /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = PetstoreClient; + 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_OPTIMIZATION_LEVEL = "-Onone"; @@ -1280,37 +1382,71 @@ }; name = Debug; }; - ADB2280332CE02FCD777CC987CD4E28A /* Release */ = { + AF5D8A65BDA6B725A14D20EC25949CE0 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 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"; 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"; MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; + MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = PromiseKit; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - C5A18280E9321A9268D1C80B7DA43967 /* Release */ = { + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; + 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; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F594C655D48020EC34B00AA63E001773 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -1327,7 +1463,10 @@ COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_PREPROCESSOR_DEFINITIONS = "RELEASE=1"; + 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; @@ -1341,28 +1480,60 @@ }; name = Release; }; - D3F110D6C2483BBC023DA8D6DFC525C3 /* Release */ = { + F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */; + baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 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; - INFOPLIST_FILE = "Target Support Files/Pods/Info.plist"; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/OMGHTTPURLRQ/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/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = OMGHTTPURLRQ; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FCA939A415B281DBA1BE816C25790182 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + 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"; 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/Pods.modulemap"; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; - PRODUCT_NAME = Pods; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; @@ -1377,8 +1548,17 @@ 03DDC7D7BA248863E8493F462ABAD118 /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { isa = XCConfigurationList; buildConfigurations = ( - 7B7ACBE5930AD378A2346DC89BAD1027 /* Debug */, - ADB2280332CE02FCD777CC987CD4E28A /* Release */, + AF5D8A65BDA6B725A14D20EC25949CE0 /* Debug */, + 6D58F928D13C57FA81A386B6364889AA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */, + FCA939A415B281DBA1BE816C25790182 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1386,8 +1566,8 @@ 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 8D1534490D941DCA47C62AC4314182AF /* Debug */, - C5A18280E9321A9268D1C80B7DA43967 /* Release */, + 84FD87D359382A37B07149A12641B965 /* Debug */, + F594C655D48020EC34B00AA63E001773 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1395,8 +1575,8 @@ 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { isa = XCConfigurationList; buildConfigurations = ( - 819D3D3D508154D9CFF3CE30C13E000E /* Debug */, - 4D5CD4E08FD8D405881C59A5535E6CE8 /* Release */, + F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */, + A1075551063662DDB4B1D70BD9D48C6E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1404,17 +1584,8 @@ 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - 28973E73A6075E48EBE277098505D118 /* Debug */, - 0D12EBEB35AC8FA740B275C8105F9152 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 8CB3C5DF3F4B6413A6F2D003B58CCF32 /* Build configuration list for PBXNativeTarget "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1361791756A3908370041AE99E5CF772 /* Debug */, - D3F110D6C2483BBC023DA8D6DFC525C3 /* Release */, + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, + 9B26D3A39011247999C097562A550399 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1422,8 +1593,17 @@ B5E28E2093F917340AF5AAA0FCE5E37D /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - 94652EA7B5323CE393BCE396E7262170 /* Debug */, - 10966F49AC953FB6BFDCBF072AF5B251 /* Release */, + 237DD903E4E61B0FFB3BB69F98EE1A1A /* Debug */, + 83EBAB51C518173D901D2A7FE10401AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C9F2C0984774847F556FBA38A5DFA380 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AEB3F05CF4CA7390DB94997A30E330AD /* Debug */, + 13D83F6E46BF53D2E6C3EB7C33E93BBF /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSObject+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSObject+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSObject+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSObject+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLConnection+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLSession+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLSession+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLSession+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/NSURLSession+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift similarity index 95% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift index 835b3633c48..20b0c2d57e4 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/PMKAlertController.swift @@ -58,8 +58,12 @@ public class PMKAlertController { private let (promise, fulfill, reject) = Promise.pendingPromise() private var retainCycle: PMKAlertController? - public enum Error: ErrorType { + public enum Error: CancellableErrorType { case Cancelled + + public var cancelled: Bool { + return self == .Cancelled + } } } diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+Promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIView+Promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m similarity index 95% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m index 3dede063bfc..2211b375c12 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.m @@ -13,9 +13,8 @@ @implementation UIViewController (PromiseKit) -- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block -{ - id vc2present = vc; +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block { + __kindof UIViewController *vc2present = vc; AnyPromise *promise = nil; if ([vc isKindOfClass:NSClassFromString(@"MFMailComposeViewController")]) { @@ -72,8 +71,7 @@ [self presentViewController:vc2present animated:animated completion:block]; promise.finally(^{ - //TODO can we be more specific? - [self dismissViewControllerAnimated:animated completion:nil]; + [vc2present.presentingViewController dismissViewControllerAnimated:animated completion:nil]; }); return promise; diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift similarity index 82% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift index 1277560d571..9d8821e3c71 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift @@ -35,7 +35,7 @@ extension UIViewController { if p.pending { presentViewController(vc, animated: animated, completion: completion) p.always { - self.dismissViewControllerAnimated(animated, completion: nil) + vc.presentingViewController!.dismissViewControllerAnimated(animated, completion: nil) } } @@ -48,7 +48,7 @@ extension UIViewController { if p.pending { presentViewController(nc, animated: animated, completion: completion) p.always { - self.dismissViewControllerAnimated(animated, completion: nil) + vc.presentingViewController!.dismissViewControllerAnimated(animated, completion: nil) } } return p @@ -56,7 +56,7 @@ extension UIViewController { return Promise(error: Error.NavigationControllerEmpty) } } - + public func promiseViewController(vc: UIImagePickerController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise { let proxy = UIImagePickerControllerProxy() vc.delegate = proxy @@ -71,7 +71,16 @@ extension UIViewController { } throw Error.NoImageFound }.always { - self.dismissViewControllerAnimated(animated, completion: nil) + vc.presentingViewController!.dismissViewControllerAnimated(animated, completion: nil) + } + } + + public func promiseViewController(vc: UIImagePickerController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<[String: AnyObject]> { + let proxy = UIImagePickerControllerProxy() + vc.delegate = proxy + presentViewController(vc, animated: animated, completion: completion) + return proxy.promise.always { + vc.presentingViewController!.dismissViewControllerAnimated(animated, completion: nil) } } } @@ -103,7 +112,7 @@ private func promise(vc: UIViewController) -> Promise { // internal scope because used by ALAssetsLibrary extension @objc class UIImagePickerControllerProxy: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { - let (promise, fulfill, reject) = Promise<[NSObject : AnyObject]>.pendingPromise() + let (promise, fulfill, reject) = Promise<[String : AnyObject]>.pendingPromise() var retainCycle: AnyObject? required override init() { diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown similarity index 84% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/README.markdown rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown index 30dba5f10be..84aabe138db 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown @@ -18,11 +18,11 @@ when(fetchImage(), getLocation()).then { image, location in PromiseKit is a thoughtful and complete implementation of promises for iOS and OS X with first-class support for **both** Objective-C *and* Swift. [![Join the chat at https://gitter.im/mxcl/PromiseKit](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mxcl/PromiseKit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ![](https://img.shields.io/cocoapods/v/PromiseKit.svg?label=Current%20Release) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg)](https://github.com/Carthage/Carthage) - +[![codebeat](https://codebeat.co/badges/6a2fc7b4-cc8f-4865-a81d-644edd38c662)](https://codebeat.co/projects/github-com-mxcl-promisekit) # Which PromiseKit Should I Use? -If you are writing a library, **use PromiseKit 1.6**. This is because PromiseKit > 2 breaks everytime Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. +If you are writing a library, [**use PromiseKit 1.x**](https://github.com/mxcl/PromiseKit/tree/legacy-1.x). This is because PromiseKit > 2 breaks everytime Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. If you are making an app then PromiseKit 3 is the best PromiseKit, you may have to make some fixes when Xcode updates, but probably you will be OK as long as you update PromiseKit when Xcode updates. @@ -85,13 +85,18 @@ github "mxcl/PromiseKit" ~> 2.0 Neither CocoaPods or Carthage will install PromiseKit 2 for an iOS 7 target. Your options are: - 1. `pod "PromiseKit", "~> 1.5"` †‡ + 1. `pod "PromiseKit", "~> 1.7"` †‡ 2. Use our [iOS 7 EZ-Bake](https://github.com/PromiseKit/EZiOS7) 3. Download our pre-built static framework (coming soon!) † There is no Swift support with PromiseKit 1.x installed via CocoaPods.
‡ PromiseKit 1.x will work as far back as iOS 5 if required. +# Support + +PromiseKit is lucky enough to have a large community behind it which is reflected in our [Gitter chat](https://gitter.im/mxcl/PromiseKit). If you're new to PromiseKit and are stumped or otherwise have a question that doesn't feel like an issue (and isn't answered in our [documentation](http://promisekit.org/introduction)) then our Gitter is a great place to go for help. Of course if you're onto something that you believe is broken or could be improved then opening a new issue is still the way to go 👍. + + # Donations PromiseKit is hundreds of hours of work almost completely by just me: [Max Howell](https://twitter.com/mxcl). I thoroughly enjoyed making PromiseKit, but nevertheless if you have found it useful then your bitcoin will give me a warm fuzzy feeling from my head right down to my toes: 1JDbV5zuym3jFw4kBCc5Z758maUD8e4dKR. diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift similarity index 98% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift index b07dc418158..8f41f7caecf 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift @@ -202,7 +202,8 @@ extension NSError { } } -func unconsume(error error: NSError, var reusingToken token: ErrorConsumptionToken? = nil) { +func unconsume(error error: NSError, reusingToken t: ErrorConsumptionToken? = nil) { + var token = t if token != nil { objc_setAssociatedObject(error, &handle, token, .OBJC_ASSOCIATION_RETAIN) } else { diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift similarity index 58% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift index a101d957476..fc1b335ca46 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift @@ -13,6 +13,25 @@ extension Promise { } } + /** + Provides an alias for the `error` property for cases where the Swift + compiler cannot disambiguate from our `error` function. + + More than likely use of this alias will never be necessary as it's + the inverse situation where Swift usually becomes confused. But + we provide this anyway just in case. + + If you absolutely cannot get Swift to accept `error` then + `errorValue` may be used instead as it returns the same thing. + + - Warning: This alias will be unavailable in PromiseKit 4.0.0 + - SeeAlso: [https://github.com/mxcl/PromiseKit/issues/347](https://github.com/mxcl/PromiseKit/issues/347) + */ + @available(*, deprecated, renamed="error", message="Temporary alias `errorValue` will eventually be removed and should only be used when the Swift compiler cannot be satisfied with `error`") + public var errorValue: ErrorType? { + return self.error + } + /** - Returns: `true` if the promise has not yet resolved. */ diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift similarity index 94% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift index a99b6977e2b..477d1109bb1 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift @@ -176,11 +176,10 @@ public class Promise { /** A `typealias` for the return values of `pendingPromise()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise()`s within the same scope, or when the promise initialization must occur outside of the caller's initialization. - ``` class Foo: BarDelegate { - var pendingPromise: Promise.PendingPromise? + var pendingPromise: Promise.PendingPromise? } - ``` + - SeeAlso: pendingPromise() */ public typealias PendingPromise = (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) @@ -251,7 +250,7 @@ public class Promise { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): - resolve(.Rejected(error)) + resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { resolve(.Fulfilled(try body(value))) @@ -280,7 +279,7 @@ public class Promise { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): - resolve(.Rejected(error)) + resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { let promise = try body(value) @@ -314,7 +313,7 @@ public class Promise { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): - resolve(.Rejected(error)) + resolve(.Rejected((error.0, error.1))) case .Fulfilled(let value): contain_zalgo(q, rejecter: resolve) { try body(value).pipe(resolve) @@ -391,6 +390,33 @@ public class Promise { } } + /** + Provides an alias for the `error` function for cases where the Swift + compiler cannot disambiguate from our `error` property. If you're + having trouble with `error`, before using this alias, first try + being as explicit as possible with the types e.g.: + + }.error { (error:ErrorType) -> Void in + //... + } + + Or even using verbose function syntax: + + }.error({ (error:ErrorType) -> Void in + //... + }) + + If you absolutely cannot get Swift to accept `error` then `onError` + may be used instead as it does the same thing. + + - Warning: This alias will be unavailable in PromiseKit 4.0.0 + - SeeAlso: [https://github.com/mxcl/PromiseKit/issues/347](https://github.com/mxcl/PromiseKit/issues/347) + */ + @available(*, deprecated, renamed="error", message="Temporary alias `onError` will eventually be removed and should only be used when the Swift compiler cannot be satisfied with `error`") + public func onError(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { + error(policy: policy, body) + } + /** The provided closure is executed when this promise is rejected giving you an opportunity to recover from the error and continue the promise chain. diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h similarity index 98% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h index a35384ab2e6..a83b3da1558 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h @@ -1,4 +1,8 @@ -#import +#if defined(__cplusplus) + #import +#else + #import +#endif #import #import #import diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift similarity index 86% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift index 22f2da367ed..b543a663469 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift @@ -17,6 +17,12 @@ import Dispatch - Returns: A new promise that resolves once all the provided promises resolve. */ public func join(promises: Promise...) -> Promise<[T]> { + return join(promises) +} + +public func join(promises: [Promise]) -> Promise<[T]> { + guard !promises.isEmpty else { return Promise<[T]>([]) } + var countdown = promises.count let barrier = dispatch_queue_create("org.promisekit.barrier.join", DISPATCH_QUEUE_CONCURRENT) var rejected = false @@ -29,8 +35,8 @@ public func join(promises: Promise...) -> Promise<[T]> { token.consumed = true // the parent Error.Join consumes all rejected = true } - - if --countdown == 0 { + countdown -= 1 + if countdown == 0 { if rejected { reject(Error.Join(promises)) } else { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift new file mode 100644 index 00000000000..4cfb1b05ee5 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift @@ -0,0 +1,31 @@ +import Foundation.NSError + +/** + Resolves with the first resolving promise from a set of promises. + + ``` + race(promise1, promise2, promise3).then { winner in + //… + } + ``` + + - Returns: A new promise that resolves when the first promise in the provided promises resolves. + - Warning: If any of the provided promises reject, the returned promise is rejected. +*/ +public func race(promises: Promise...) -> Promise { + return try! race(promises) // race only throws when the array param is empty, which is not possible from this + // variadic paramater version, so we can safely use `try!` +} + +public func race(promises: [Promise]) throws -> Promise { + guard !promises.isEmpty else { + let message = "Cannot race with an empty list of runners (Promises)" + throw NSError(domain: PMKErrorDomain, code: PMKInvalidUsageError, userInfo: ["messaage": message]) + } + + return Promise(sealant: { resolve in + for promise in promises { + promise.pipe(resolve) + } + }) +} diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift similarity index 96% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift index f6ab1324291..7c01db446b8 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift @@ -28,8 +28,9 @@ private func _when(promises: [Promise]) -> Promise { } case .Fulfilled: guard rootPromise.pending else { return } - progress.completedUnitCount++ - if --countdown == 0 { + progress.completedUnitCount += 1 + countdown -= 1 + if countdown == 0 { fulfill() } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 00000000000..a6c4594242e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 00000000000..6b71676a9bd --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 00000000000..d1f125fab6b --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 00000000000..772ef0b2bca --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +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_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 00000000000..c1aea25c248 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.1.5 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist similarity index 92% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist index ce3a3137315..793d31a9fdd 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.${PRODUCT_NAME:rfc1034identifier} + ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-dummy.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-dummy.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-dummy.m diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-prefix.pch diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-umbrella.h similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-umbrella.h rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ-umbrella.h diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.modulemap diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig new file mode 100644 index 00000000000..256da76db28 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/OMGHTTPURLRQ.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist new file mode 100644 index 00000000000..cba258550bd --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m new file mode 100644 index 00000000000..749b412f85c --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PetstoreClient : NSObject +@end +@implementation PodsDummy_PetstoreClient +@end diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch new file mode 100644 index 00000000000..aa992a4adb2 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h new file mode 100644 index 00000000000..75c63f7c53e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double PetstoreClientVersionNumber; +FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[]; + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap new file mode 100644 index 00000000000..7fdfc46cf79 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap @@ -0,0 +1,6 @@ +framework module PetstoreClient { + umbrella header "PetstoreClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig new file mode 100644 index 00000000000..e58b19aae46 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" "$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_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist new file mode 100644 index 00000000000..2243fe6e27d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown similarity index 96% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown index a24fb37c814..1b1501b1eb5 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -31,4 +31,4 @@ See README.markdown for full license text. ## PromiseKit @see README -Generated by CocoaPods - http://cocoapods.org +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist similarity index 97% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.plist rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist index 0dca0acc18f..990f8a6c29b 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/Pods/Pods-acknowledgements.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -57,7 +57,7 @@ THE SOFTWARE. FooterText - Generated by CocoaPods - http://cocoapods.org + Generated by CocoaPods - https://cocoapods.org Title Type diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m new file mode 100644 index 00000000000..6236440163b --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClient : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClient +@end diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh new file mode 100755 index 00000000000..f590fba3ba0 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -0,0 +1,97 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/OMGHTTPURLRQ/OMGHTTPURLRQ.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" + install_framework "$BUILT_PRODUCTS_DIR/PromiseKit/PromiseKit.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/OMGHTTPURLRQ/OMGHTTPURLRQ.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" + install_framework "$BUILT_PRODUCTS_DIR/PromiseKit/PromiseKit.framework" +fi diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh new file mode 100755 index 00000000000..e768f92993e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h new file mode 100644 index 00000000000..b68fbb9611f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[]; + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig new file mode 100644 index 00000000000..6cbf6b29f2e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -0,0 +1,11 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" "$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/OMGHTTPURLRQ/OMGHTTPURLRQ.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 "OMGHTTPURLRQ" -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_ROOT = ${SRCROOT}/Pods +SWIFT_INSTALL_OBJC_HEADER = NO diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap new file mode 100644 index 00000000000..ef919b6c0d1 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClient { + umbrella header "Pods-SwaggerClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig new file mode 100644 index 00000000000..6cbf6b29f2e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -0,0 +1,11 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" "$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/OMGHTTPURLRQ/OMGHTTPURLRQ.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 "OMGHTTPURLRQ" -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_ROOT = ${SRCROOT}/Pods +SWIFT_INSTALL_OBJC_HEADER = NO diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist new file mode 100644 index 00000000000..2243fe6e27d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown new file mode 100644 index 00000000000..102af753851 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist new file mode 100644 index 00000000000..7acbad1eabb --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m new file mode 100644 index 00000000000..bb17fa2b80f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClientTests : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClientTests +@end diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh new file mode 100755 index 00000000000..893c16a6313 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh new file mode 100755 index 00000000000..e768f92993e --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h new file mode 100644 index 00000000000..fb4cae0c0fd --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[]; + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig new file mode 100644 index 00000000000..a03fe773e57 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -0,0 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" "$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/OMGHTTPURLRQ/OMGHTTPURLRQ.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_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap new file mode 100644 index 00000000000..a848da7ffb3 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClientTests { + umbrella header "Pods-SwaggerClientTests-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig new file mode 100644 index 00000000000..a03fe773e57 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -0,0 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" "$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/OMGHTTPURLRQ/OMGHTTPURLRQ.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_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist new file mode 100644 index 00000000000..c11c2ee42e9 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.1.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch new file mode 100644 index 00000000000..aa992a4adb2 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig new file mode 100644 index 00000000000..83e52988951 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PromiseKit +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/OMGHTTPURLRQ" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "Foundation" -framework "QuartzCore" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SWIFT_INSTALL_OBJC_HEADER = NO diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..3d557a9280f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -0,0 +1,550 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */; }; + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */; }; + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6D4EFB891C692C6300B96B06 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6D4EFB901C692C6300B96B06; + remoteInfo = SwaggerClient; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 289E8A9E9C0BB66AD190C7C6 /* 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 = ""; }; + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 6D4EFB991C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 6D4EFB9E1C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 6D4EFBA01C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwaggerClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFBAB1C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A638467ACFB30852DEA51F7A /* 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 = ""; }; + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6D4EFB8E1C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA21C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0CAA98BEFA303B94D3664C7D /* Pods */ = { + isa = PBXGroup; + children = ( + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C07EC0A94AA0F86D60668B32 /* Pods.framework */, + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 6D4EFB881C692C6300B96B06 = { + isa = PBXGroup; + children = ( + 6D4EFB931C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, + 6D4EFB921C692C6300B96B06 /* Products */, + 3FABC56EC0BA84CBF4F99564 /* Frameworks */, + 0CAA98BEFA303B94D3664C7D /* Pods */, + ); + sourceTree = ""; + }; + 6D4EFB921C692C6300B96B06 /* Products */ = { + isa = PBXGroup; + children = ( + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */, + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 6D4EFB931C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXGroup; + children = ( + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */, + 6D4EFB961C692C6300B96B06 /* ViewController.swift */, + 6D4EFB981C692C6300B96B06 /* Main.storyboard */, + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */, + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */, + 6D4EFBA01C692C6300B96B06 /* Info.plist */, + ); + path = SwaggerClient; + sourceTree = ""; + }; + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 6D4EFBAB1C692C6300B96B06 /* Info.plist */, + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */, + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */, + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */, + ); + path = SwaggerClientTests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 6D4EFB901C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; + buildPhases = ( + 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, + 6D4EFB8D1C692C6300B96B06 /* Sources */, + 6D4EFB8E1C692C6300B96B06 /* Frameworks */, + 6D4EFB8F1C692C6300B96B06 /* Resources */, + 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwaggerClient; + productName = SwaggerClient; + productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; + productType = "com.apple.product-type.application"; + }; + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; + buildPhases = ( + 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, + 6D4EFBA11C692C6300B96B06 /* Sources */, + 6D4EFBA21C692C6300B96B06 /* Frameworks */, + 6D4EFBA31C692C6300B96B06 /* Resources */, + 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */, + ); + name = SwaggerClientTests; + productName = SwaggerClientTests; + productReference = 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 6D4EFB891C692C6300B96B06 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0720; + LastUpgradeCheck = 0720; + ORGANIZATIONNAME = Swagger; + TargetAttributes = { + 6D4EFB901C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + }; + 6D4EFBA41C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + TestTargetID = 6D4EFB901C692C6300B96B06; + }; + }; + }; + buildConfigurationList = 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 6D4EFB881C692C6300B96B06; + productRefGroup = 6D4EFB921C692C6300B96B06 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 6D4EFB901C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 6D4EFB8F1C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */, + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */, + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA31C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 6D4EFB8D1C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */, + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA11C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */, + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */, + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 6D4EFB901C692C6300B96B06 /* SwaggerClient */; + targetProxy = 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 6D4EFB981C692C6300B96B06 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB991C692C6300B96B06 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB9E1C692C6300B96B06 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 6D4EFBAC1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + 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_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "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; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 6D4EFBAD1C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + 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_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + 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 = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 6D4EFBAF1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 6D4EFBB01C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 6D4EFBB21C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Debug; + }; + 6D4EFBB31C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAC1C692C6300B96B06 /* Debug */, + 6D4EFBAD1C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAF1C692C6300B96B06 /* Debug */, + 6D4EFBB01C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBB21C692C6300B96B06 /* Debug */, + 6D4EFBB31C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme new file mode 100644 index 00000000000..5ba034cec55 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..9b3fa18954f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift new file mode 100644 index 00000000000..3769667ad9c --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(application: UIApplication) { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..eeea76c2db5 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,73 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000000..2e721e1833f --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard new file mode 100644 index 00000000000..3a2a49bad8c --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Info.plist new file mode 100644 index 00000000000..bb71d00fa8a --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/Info.plist @@ -0,0 +1,59 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift new file mode 100644 index 00000000000..cd7e9a16761 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift @@ -0,0 +1,25 @@ +// +// ViewController.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist new file mode 100644 index 00000000000..802f84f540d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift similarity index 95% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 38948737687..b52fe4a0fa8 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -32,7 +32,8 @@ class StoreAPITests: XCTestCase { order.complete = false order.quantity = 10 order.shipDate = NSDate() - order.status = .Placed + // use explicit naming to reference the enum so that we test we don't regress on enum naming + order.status = Order.Status.Placed let expectation = self.expectationWithDescription("testPlaceOrder") StoreAPI.placeOrder(body: order).then { order -> Void in XCTAssert(order.id == 1000, "invalid id") diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift similarity index 100% rename from samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift rename to samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/pom.xml b/samples/client/petstore/swift/promisekit/SwaggerClientTests/pom.xml new file mode 100644 index 00000000000..fdaec7c26a6 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/pom.xml @@ -0,0 +1,65 @@ + + 4.0.0 + io.swagger + SwiftPromiseKitPetstoreClientTests + pom + 1.0-SNAPSHOT + Swift PromiseKit Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + install-pods + pre-integration-test + + exec + + + pod + + install + + + + + xcodebuild-test + integration-test + + exec + + + xcodebuild + + -workspace + SwaggerClient.xcworkspace + -scheme + SwaggerClient + test + -destination + platform=iOS Simulator,name=iPhone 6,OS=9.3 + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/default-es6/git_push.sh b/samples/client/petstore/swift/promisekit/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default-es6/git_push.sh rename to samples/client/petstore/swift/promisekit/git_push.sh diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 62492c17d80..90b44ec3e73 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 976ee7acd48..7c3fed82fa3 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 79f6326b99c..d237038d7da 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json index 0819b27f295..04801e691a9 100644 --- a/samples/client/petstore/typescript-angular/package.json +++ b/samples/client/petstore/typescript-angular/package.json @@ -1,6 +1,7 @@ { "name": "petstore-typescript-node-sample", "version": "1.0.0", + "repository": "GIT_USER_ID/GIT_REPO_ID", "description": "Sample of generated TypeScript petstore client", "main": "api.js", "scripts": { @@ -8,8 +9,8 @@ "test": "tsc --target ES6 && node client.js", "clean": "rm -Rf node_modules/ typings/ *.js" }, - "author": "Mads M. Tandrup", - "license": "Apache 2.0", + "author": "Swagger Codegen Contributors & Mads M. Tandrup", + "license": "Apache-2.0", "dependencies": { "request": "^2.60.0", "angular": "^1.4.3" diff --git a/samples/client/petstore/csharp/SwaggerClientTest/pom.xml b/samples/client/petstore/typescript-angular/pom.xml similarity index 77% rename from samples/client/petstore/csharp/SwaggerClientTest/pom.xml rename to samples/client/petstore/typescript-angular/pom.xml index 46304c21621..6072fc71140 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/pom.xml +++ b/samples/client/petstore/typescript-angular/pom.xml @@ -1,10 +1,10 @@ 4.0.0 com.wordnik - CsharpPetstoreClientTests + TypeScriptAngularPestoreClientTests pom 1.0-SNAPSHOT - C# Swagger Petstore Client + TS Angular Petstore Client @@ -26,27 +26,30 @@ exec-maven-plugin 1.2.1 - + - mono-test + npm-test integration-test exec - mono-nunit.sh + npm + + test + diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index e2121b52c0b..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 618b0c23624..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index f52b407d126..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 8120c59916e..0fdbf4a4ded 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index e2121b52c0b..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 618b0c23624..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index f52b407d126..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index cab5097a4ed..8447881dafc 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201604282253", + "version": "0.0.1-SNAPSHOT.201605120027", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -16,17 +16,30 @@ "build": "typings install && tsc" }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }, "publishConfig":{ "registry":"https://skimdb.npmjs.com/registry" diff --git a/samples/client/petstore/typescript-fetch/api.ts b/samples/client/petstore/typescript-fetch/api.ts deleted file mode 100644 index 0c8f4201e4c..00000000000 --- a/samples/client/petstore/typescript-fetch/api.ts +++ /dev/null @@ -1,859 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - - -export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered' -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - - -export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * 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 (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/assign.ts b/samples/client/petstore/typescript-fetch/assign.ts deleted file mode 100644 index 040f87d7d98..00000000000 --- a/samples/client/petstore/typescript-fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target, ...args) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/.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 +# Thsi 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/default/LICENSE b/samples/client/petstore/typescript-fetch/builds/default/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/typescript-fetch/builds/default/README.md b/samples/client/petstore/typescript-fetch/builds/default/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts new file mode 100644 index 00000000000..3882e79a66c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -0,0 +1,1122 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw 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 + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/default/git_push.sh b/samples/client/petstore/typescript-fetch/builds/default/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/default/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default/package.json b/samples/client/petstore/typescript-fetch/builds/default/package.json similarity index 69% rename from samples/client/petstore/typescript-fetch/default/package.json rename to samples/client/petstore/typescript-fetch/builds/default/package.json index 84cf629d931..97e572353a3 100644 --- a/samples/client/petstore/typescript-fetch/default/package.json +++ b/samples/client/petstore/typescript-fetch/builds/default/package.json @@ -1,18 +1,19 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, + "license": "Apache-2.0", "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", - "typings": "^0.8.1" + "typings": "^1.0.4" } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-fetch/builds/default/pom.xml b/samples/client/petstore/typescript-fetch/builds/default/pom.xml new file mode 100644 index 00000000000..afcb5847ad9 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.wordnik + TypeScriptAngularBuildPestoreClientTests + pom + 1.0-SNAPSHOT + TS Angular Build Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + integration-test + + exec + + + npm + + install + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/default/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/default/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/default/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/default/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/default/typings.json b/samples/client/petstore/typescript-fetch/builds/default/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/default/typings.json rename to samples/client/petstore/typescript-fetch/builds/default/typings.json index eeca5afde97..a82ea152b4a 100644 --- a/samples/client/petstore/typescript-fetch/default/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/default/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/.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 +# Thsi 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/es6-target/LICENSE b/samples/client/petstore/typescript-fetch/builds/es6-target/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/README.md b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts new file mode 100644 index 00000000000..15a61ab6961 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -0,0 +1,1121 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw 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 + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/git_push.sh b/samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default-es6/package.json b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json similarity index 74% rename from samples/client/petstore/typescript-fetch/default-es6/package.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/package.json index 84cf629d931..b2b5cc240dc 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/package.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json @@ -1,7 +1,7 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, + "license": "Apache-2.0", "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", @@ -9,10 +9,10 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", - "typings": "^0.8.1" + "typings": "^1.0.4" } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml b/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml new file mode 100644 index 00000000000..52c43b2cd0d --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.wordnik + TypeScriptAngularBuildES6PestoreClientTests + pom + 1.0-SNAPSHOT + TS Angular Build ES6 Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + integration-test + + exec + + + npm + + install + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/default-es6/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json index 9d5f166e764..06a8e0437b9 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/default-es6/typings.json b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json similarity index 86% rename from samples/client/petstore/typescript-fetch/default-es6/typings.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/typings.json index 3ce24427fc6..2ec50862694 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json @@ -1,7 +1,7 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { + "globalDependencies": { "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.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 +# Thsi 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-npm-version/LICENSE b/samples/client/petstore/typescript-fetch/builds/with-npm-version/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` 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 new file mode 100644 index 00000000000..3882e79a66c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -0,0 +1,1122 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw 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 + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw 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 + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh b/samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json similarity index 70% rename from samples/client/petstore/typescript-fetch/with-package-metadata/package.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json index ab2a67c51d0..c1d30ab9493 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json @@ -1,18 +1,19 @@ { "name": "@swagger/typescript-fetch-petstore", "version": "0.0.1", - "private": true, + "license": "Apache-2.0", "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", - "typings": "^0.8.1" + "typings": "^1.0.4" } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml b/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml new file mode 100644 index 00000000000..0e7264cffb5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.wordnik + TypeScriptAngularBuildWithNPMVersionPestoreClientTests + pom + 1.0-SNAPSHOT + TS Angular Build With NPM Version Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + integration-test + + exec + + + npm + + install + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/with-package-metadata/typings.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json index eeca5afde97..a82ea152b4a 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/default-es6/README.md b/samples/client/petstore/typescript-fetch/default-es6/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/api.ts b/samples/client/petstore/typescript-fetch/default-es6/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -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 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 interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default-es6/assign.ts b/samples/client/petstore/typescript-fetch/default-es6/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/README.md b/samples/client/petstore/typescript-fetch/default/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/api.ts b/samples/client/petstore/typescript-fetch/default/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -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 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 interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default/assign.ts b/samples/client/petstore/typescript-fetch/default/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/package.json b/samples/client/petstore/typescript-fetch/package.json deleted file mode 100644 index 722c87cc323..00000000000 --- a/samples/client/petstore/typescript-fetch/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "private": true, - "dependencies": { - "isomorphic-fetch": "^2.2.1" - }, - "devDependencies": { - "typescript": "^1.8.10", - "typings": "^0.8.1" - } -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/package.json b/samples/client/petstore/typescript-fetch/tests/default/package.json new file mode 100644 index 00000000000..b95b42bc29e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/package.json @@ -0,0 +1,27 @@ +{ + "private": true, + "dependencies": { + "chai": "^3.5.0" + }, + "devDependencies": { + "browserify": "^13.0.1", + "ts-loader": "^0.8.2", + "tsify": "^0.16.0", + "typescript": "^1.8.10", + "typings": "^1.0.4", + "webpack": "^1.13.0" + }, + "scripts": { + "prepublish": "./scripts/prepublish.sh", + "pretest": "npm install mocha", + "test": "mocha" + }, + "name": "typescript-fetch-test", + "version": "1.0.0", + "directories": { + "test": "test" + }, + "author": "", + "license": "ISC", + "description": "" +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/pom.xml b/samples/client/petstore/typescript-fetch/tests/default/pom.xml new file mode 100644 index 00000000000..9108f6759a9 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.wordnik + TypeScriptFetchPestoreClientTests + pom + 1.0-SNAPSHOT + TS Fetch default Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + npm-test + integration-test + + exec + + + npm + + test + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html new file mode 100644 index 00000000000..5d378bac582 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html @@ -0,0 +1,26 @@ + + + + Mocha Tests + + + +

+ + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html new file mode 100644 index 00000000000..ace737c7ccd --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html @@ -0,0 +1,27 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh new file mode 100755 index 00000000000..3c0dfb05953 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +npm install ../../builds/default +typings install + +# Build Node.js +tsc + +# Build Webpack +webpack + +# Build browserify +browserify test -p [ tsify ] > ./dist/test.browserify-bundle.js diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts new file mode 100644 index 00000000000..04b2c032a34 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts @@ -0,0 +1,63 @@ +import {expect} from 'chai'; +import {PetApi, Pet, Category} from 'typescript-fetch-api'; + +describe('PetApi', () => { + let api: PetApi; + let fixture: Pet = createTestFixture(); + + beforeEach(() => { + api = new PetApi(); + }); + + it('should add and delete Pet', () => { + return api.addPet({ body: fixture }).then(() => { + }); + }); + + it('should get Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + result.name = 'newname'; + return api.updatePet({ body: result }).then(() => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return api.deletePet({ petId: fixture.id }); + }); + + it('should not contain deleted Pet', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + return expect(err).to.exist; + }); + }); +}); + +function createTestFixture(ts = Date.now()) { + const category: Category = { + 'id': ts, + 'name': `category${ts}`, + }; + + const pet: Pet = { + 'id': ts, + 'name': `pet${ts}`, + 'category': category, + 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], + 'status': 'available', + 'tags': [] + }; + + return pet; +}; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts new file mode 100644 index 00000000000..420def0ab62 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts @@ -0,0 +1,18 @@ +import {expect} from 'chai'; +import {StoreApi} from 'typescript-fetch-api'; + +describe('StoreApi', function() { + let api: StoreApi; + + beforeEach(function() { + api = new StoreApi(); + }); + + it('should get inventory', function() { + return api.getInventory().then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + +}); + diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/index.ts b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts new file mode 100644 index 00000000000..29369a2d0e2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts @@ -0,0 +1,2 @@ +import './PetApi'; +import './StoreApi'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts new file mode 100644 index 00000000000..12ea969970a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 dist/test diff --git a/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json new file mode 100644 index 00000000000..e47c2647e01 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "noImplicitAny": true, + "sourceMap": false, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/typings.json b/samples/client/petstore/typescript-fetch/tests/default/typings.json new file mode 100644 index 00000000000..d05709202f7 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/typings.json @@ -0,0 +1,9 @@ +{ + "name": "typescript-fetch-test", + "version": false, + "globalDependencies": { + "chai": "registry:dt/chai#3.4.0+20160317120654", + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "mocha": "registry:dt/mocha#2.2.5+20160317120654" + } +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js new file mode 100644 index 00000000000..d3332281c5c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js @@ -0,0 +1,30 @@ +const webpack = require('webpack'); + +module.exports = { + entry: { + app: './test/index.ts', + vendor: [ + // libraries + 'typescript-fetch-api' + ], + }, + output: { + filename: './dist/test.webpack-bundle.js' + }, + plugins: [ + new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'./dist/vendor.webpack-bundle.js') + ], + resolve: { + // Add `.ts` and `.tsx` as a resolvable extension. + extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'] + }, + module: { + loaders: [ + // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` + { + test: /\.tsx?$/, + loader: 'ts-loader' + } + ] + } +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tsconfig.json b/samples/client/petstore/typescript-fetch/tsconfig.json deleted file mode 100644 index fc93dc1610e..00000000000 --- a/samples/client/petstore/typescript-fetch/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "target": "es5" - }, - "exclude": [ - "node_modules", - "typings/browser", - "typings/main", - "typings/main.d.ts" - ] -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/typings.json b/samples/client/petstore/typescript-fetch/typings.json deleted file mode 100644 index c22f086f7f0..00000000000 --- a/samples/client/petstore/typescript-fetch/typings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": false, - "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", - "node": "registry:dt/node#4.0.0+20160423143914", - "isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module" - } -} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md b/samples/client/petstore/typescript-fetch/with-package-metadata/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -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 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 interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * 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 (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ 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 568335b5769..6eaa16cfd97 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -1,6 +1,6 @@ import request = require('request'); import http = require('http'); -import promise = require('bluebird'); +import Promise = require('bluebird'); let defaultBasePath = 'http://petstore.swagger.io/v2'; @@ -128,6 +128,7 @@ export enum PetApiApiKeys { export class PetApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), @@ -148,6 +149,10 @@ export class PetApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: PetApiApiKeys, value: string) { this.authentications[PetApiApiKeys[key]].apiKey = value; } @@ -177,12 +182,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -198,18 +203,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Deletes a pet @@ -234,12 +240,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -254,18 +260,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Finds Pets by status @@ -285,12 +292,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -305,18 +312,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Finds Pets by tags @@ -336,12 +344,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -356,18 +364,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Find pet by ID @@ -389,12 +398,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -411,18 +420,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Update an existing pet @@ -438,12 +448,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -459,18 +469,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Updates a pet in the store with form data @@ -502,12 +513,12 @@ export class PetApi { formParams['status'] = status; } - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -522,18 +533,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * uploads an image @@ -566,12 +578,12 @@ export class PetApi { } useFormData = true; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -586,18 +598,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } export enum StoreApiApiKeys { @@ -607,6 +620,7 @@ export enum StoreApiApiKeys { export class StoreApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), @@ -627,6 +641,10 @@ export class StoreApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: StoreApiApiKeys, value: string) { this.authentications[StoreApiApiKeys[key]].apiKey = value; } @@ -662,12 +680,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -680,18 +698,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Returns pet inventories by status @@ -706,12 +725,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -726,18 +745,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Find purchase order by ID @@ -759,12 +779,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -777,18 +797,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Place an order for a pet @@ -804,12 +825,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -823,18 +844,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } export enum UserApiApiKeys { @@ -844,6 +866,7 @@ export enum UserApiApiKeys { export class UserApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), @@ -864,6 +887,10 @@ export class UserApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: UserApiApiKeys, value: string) { this.authentications[UserApiApiKeys[key]].apiKey = value; } @@ -893,12 +920,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -912,18 +939,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Creates list of users with given input array @@ -939,12 +967,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -958,18 +986,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Creates list of users with given input array @@ -985,12 +1014,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -1004,18 +1033,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Delete user @@ -1037,12 +1067,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1055,18 +1085,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Get user by user name @@ -1088,12 +1119,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1106,18 +1137,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Logs user into the system @@ -1142,12 +1174,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1160,18 +1192,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Logs out current logged in user session @@ -1186,12 +1219,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1204,18 +1237,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Updated user @@ -1238,12 +1272,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -1257,17 +1291,18 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } diff --git a/samples/client/petstore/typescript-node/npm/.gitignore b/samples/client/petstore/typescript-node/npm/.gitignore new file mode 100644 index 00000000000..69a24fb7446 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/.gitignore @@ -0,0 +1,2 @@ +*.js +*.map \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore b/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore new file mode 100644 index 00000000000..7810b90fab5 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/.swagger-codegen-ignore @@ -0,0 +1,2 @@ +tsconfig.json +package.json diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts index 7a1a1ff8199..8d1bd4acbb5 100644 --- a/samples/client/petstore/typescript-node/npm/api.d.ts +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -1,5 +1,6 @@ import request = require('request'); import http = require('http'); +import Promise = require('bluebird'); export declare class Category { 'id': number; 'name': string; @@ -78,12 +79,14 @@ export declare enum PetApiApiKeys { export declare class PetApi { protected basePath: string; protected defaultHeaders: any; + protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'api_key': ApiKeyAuth; 'petstore_auth': OAuth; + 'api_key': ApiKeyAuth; }; constructor(basePath?: string); + useQuerystring: boolean; setApiKey(key: PetApiApiKeys, value: string): void; accessToken: string; private extendObj(objA, objB); @@ -126,12 +129,14 @@ export declare enum StoreApiApiKeys { export declare class StoreApi { protected basePath: string; protected defaultHeaders: any; + protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'api_key': ApiKeyAuth; 'petstore_auth': OAuth; + 'api_key': ApiKeyAuth; }; constructor(basePath?: string); + useQuerystring: boolean; setApiKey(key: StoreApiApiKeys, value: string): void; accessToken: string; private extendObj(objA, objB); @@ -160,12 +165,14 @@ export declare enum UserApiApiKeys { export declare class UserApi { protected basePath: string; protected defaultHeaders: any; + protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'api_key': ApiKeyAuth; 'petstore_auth': OAuth; + 'api_key': ApiKeyAuth; }; constructor(basePath?: string); + useQuerystring: boolean; setApiKey(key: UserApiApiKeys, value: string): void; accessToken: string; private extendObj(objA, objB); diff --git a/samples/client/petstore/typescript-node/npm/api.js b/samples/client/petstore/typescript-node/npm/api.js deleted file mode 100644 index b8426c2b644..00000000000 --- a/samples/client/petstore/typescript-node/npm/api.js +++ /dev/null @@ -1,1070 +0,0 @@ -var request = require('request'); -var promise = require('bluebird'); -var defaultBasePath = 'http://petstore.swagger.io/v2'; -var Category = (function () { - function Category() { - } - return Category; -})(); -exports.Category = Category; -var Order = (function () { - function Order() { - } - return Order; -})(); -exports.Order = Order; -var Order; -(function (Order) { - (function (StatusEnum) { - StatusEnum[StatusEnum["StatusEnum_placed"] = 'placed'] = "StatusEnum_placed"; - StatusEnum[StatusEnum["StatusEnum_approved"] = 'approved'] = "StatusEnum_approved"; - StatusEnum[StatusEnum["StatusEnum_delivered"] = 'delivered'] = "StatusEnum_delivered"; - })(Order.StatusEnum || (Order.StatusEnum = {})); - var StatusEnum = Order.StatusEnum; -})(Order = exports.Order || (exports.Order = {})); -var Pet = (function () { - function Pet() { - } - return Pet; -})(); -exports.Pet = Pet; -var Pet; -(function (Pet) { - (function (StatusEnum) { - StatusEnum[StatusEnum["StatusEnum_available"] = 'available'] = "StatusEnum_available"; - StatusEnum[StatusEnum["StatusEnum_pending"] = 'pending'] = "StatusEnum_pending"; - StatusEnum[StatusEnum["StatusEnum_sold"] = 'sold'] = "StatusEnum_sold"; - })(Pet.StatusEnum || (Pet.StatusEnum = {})); - var StatusEnum = Pet.StatusEnum; -})(Pet = exports.Pet || (exports.Pet = {})); -var Tag = (function () { - function Tag() { - } - return Tag; -})(); -exports.Tag = Tag; -var User = (function () { - function User() { - } - return User; -})(); -exports.User = User; -var HttpBasicAuth = (function () { - function HttpBasicAuth() { - } - HttpBasicAuth.prototype.applyToRequest = function (requestOptions) { - requestOptions.auth = { - username: this.username, password: this.password - }; - }; - return HttpBasicAuth; -})(); -exports.HttpBasicAuth = HttpBasicAuth; -var ApiKeyAuth = (function () { - function ApiKeyAuth(location, paramName) { - this.location = location; - this.paramName = paramName; - } - ApiKeyAuth.prototype.applyToRequest = function (requestOptions) { - if (this.location == "query") { - requestOptions.qs[this.paramName] = this.apiKey; - } - else if (this.location == "header") { - requestOptions.headers[this.paramName] = this.apiKey; - } - }; - return ApiKeyAuth; -})(); -exports.ApiKeyAuth = ApiKeyAuth; -var OAuth = (function () { - function OAuth() { - } - OAuth.prototype.applyToRequest = function (requestOptions) { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; - }; - return OAuth; -})(); -exports.OAuth = OAuth; -var VoidAuth = (function () { - function VoidAuth() { - } - VoidAuth.prototype.applyToRequest = function (requestOptions) { - }; - return VoidAuth; -})(); -exports.VoidAuth = VoidAuth; -(function (PetApiApiKeys) { - PetApiApiKeys[PetApiApiKeys["api_key"] = 0] = "api_key"; -})(exports.PetApiApiKeys || (exports.PetApiApiKeys = {})); -var PetApiApiKeys = exports.PetApiApiKeys; -var PetApi = (function () { - function PetApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; - this.defaultHeaders = {}; - this.authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - }; - if (password) { - if (basePath) { - this.basePath = basePath; - } - } - else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername; - } - } - } - PetApi.prototype.setApiKey = function (key, value) { - this.authentications[PetApiApiKeys[key]].apiKey = value; - }; - Object.defineProperty(PetApi.prototype, "accessToken", { - set: function (token) { - this.authentications.petstore_auth.accessToken = token; - }, - enumerable: true, - configurable: true - }); - PetApi.prototype.extendObj = function (objA, objB) { - for (var key in objB) { - if (objB.hasOwnProperty(key)) { - objA[key] = objB[key]; - } - } - return objA; - }; - PetApi.prototype.addPet = function (body) { - var localVarPath = this.basePath + '/pet'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.deletePet = function (petId, apiKey) { - var localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling deletePet.'); - } - headerParams['api_key'] = apiKey; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.findPetsByStatus = function (status) { - var localVarPath = this.basePath + '/pet/findByStatus'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (status !== undefined) { - queryParameters['status'] = status; - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.findPetsByTags = function (tags) { - var localVarPath = this.basePath + '/pet/findByTags'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.getPetById = function (petId) { - var localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling getPetById.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.updatePet = function (body) { - var localVarPath = this.basePath + '/pet'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'PUT', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.updatePetWithForm = function (petId, name, status) { - var localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); - } - var useFormData = false; - if (name !== undefined) { - formParams['name'] = name; - } - if (status !== undefined) { - formParams['status'] = status; - } - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - PetApi.prototype.uploadFile = function (petId, additionalMetadata, file) { - var localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(petId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); - } - var useFormData = false; - if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = additionalMetadata; - } - if (file !== undefined) { - formParams['file'] = file; - } - useFormData = true; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - return PetApi; -})(); -exports.PetApi = PetApi; -(function (StoreApiApiKeys) { - StoreApiApiKeys[StoreApiApiKeys["api_key"] = 0] = "api_key"; -})(exports.StoreApiApiKeys || (exports.StoreApiApiKeys = {})); -var StoreApiApiKeys = exports.StoreApiApiKeys; -var StoreApi = (function () { - function StoreApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; - this.defaultHeaders = {}; - this.authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - }; - if (password) { - if (basePath) { - this.basePath = basePath; - } - } - else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername; - } - } - } - StoreApi.prototype.setApiKey = function (key, value) { - this.authentications[StoreApiApiKeys[key]].apiKey = value; - }; - Object.defineProperty(StoreApi.prototype, "accessToken", { - set: function (token) { - this.authentications.petstore_auth.accessToken = token; - }, - enumerable: true, - configurable: true - }); - StoreApi.prototype.extendObj = function (objA, objB) { - for (var key in objB) { - if (objB.hasOwnProperty(key)) { - objA[key] = objB[key]; - } - } - return objA; - }; - StoreApi.prototype.deleteOrder = function (orderId) { - var localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (orderId === null || orderId === undefined) { - throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - StoreApi.prototype.getInventory = function () { - var localVarPath = this.basePath + '/store/inventory'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - StoreApi.prototype.getOrderById = function (orderId) { - var localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (orderId === null || orderId === undefined) { - throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - StoreApi.prototype.placeOrder = function (body) { - var localVarPath = this.basePath + '/store/order'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - return StoreApi; -})(); -exports.StoreApi = StoreApi; -(function (UserApiApiKeys) { - UserApiApiKeys[UserApiApiKeys["api_key"] = 0] = "api_key"; -})(exports.UserApiApiKeys || (exports.UserApiApiKeys = {})); -var UserApiApiKeys = exports.UserApiApiKeys; -var UserApi = (function () { - function UserApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; - this.defaultHeaders = {}; - this.authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - }; - if (password) { - if (basePath) { - this.basePath = basePath; - } - } - else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername; - } - } - } - UserApi.prototype.setApiKey = function (key, value) { - this.authentications[UserApiApiKeys[key]].apiKey = value; - }; - Object.defineProperty(UserApi.prototype, "accessToken", { - set: function (token) { - this.authentications.petstore_auth.accessToken = token; - }, - enumerable: true, - configurable: true - }); - UserApi.prototype.extendObj = function (objA, objB) { - for (var key in objB) { - if (objB.hasOwnProperty(key)) { - objA[key] = objB[key]; - } - } - return objA; - }; - UserApi.prototype.createUser = function (body) { - var localVarPath = this.basePath + '/user'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.createUsersWithArrayInput = function (body) { - var localVarPath = this.basePath + '/user/createWithArray'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.createUsersWithListInput = function (body) { - var localVarPath = this.basePath + '/user/createWithList'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.deleteUser = function (username) { - var localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling deleteUser.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.getUserByName = function (username) { - var localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling getUserByName.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.loginUser = function (username, password) { - var localVarPath = this.basePath + '/user/login'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (username !== undefined) { - queryParameters['username'] = username; - } - if (password !== undefined) { - queryParameters['password'] = password; - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.logoutUser = function () { - var localVarPath = this.basePath + '/user/logout'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - UserApi.prototype.updateUser = function (username, body) { - var localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling updateUser.'); - } - var useFormData = false; - var localVarDeferred = promise.defer(); - var requestOptions = { - method: 'PUT', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; - } - else { - requestOptions.form = formParams; - } - } - request(requestOptions, function (error, response, body) { - if (error) { - localVarDeferred.reject(error); - } - else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } - else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; - }; - return UserApi; -})(); -exports.UserApi = UserApi; -//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/api.js.map b/samples/client/petstore/typescript-node/npm/api.js.map deleted file mode 100644 index 850f5471489..00000000000 --- a/samples/client/petstore/typescript-node/npm/api.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":["Category","Category.constructor","Order","Order.constructor","Order.StatusEnum","Pet","Pet.constructor","Pet.StatusEnum","Tag","Tag.constructor","User","User.constructor","HttpBasicAuth","HttpBasicAuth.constructor","HttpBasicAuth.applyToRequest","ApiKeyAuth","ApiKeyAuth.constructor","ApiKeyAuth.applyToRequest","OAuth","OAuth.constructor","OAuth.applyToRequest","VoidAuth","VoidAuth.constructor","VoidAuth.applyToRequest","PetApiApiKeys","PetApi","PetApi.constructor","PetApi.setApiKey","PetApi.accessToken","PetApi.extendObj","PetApi.addPet","PetApi.deletePet","PetApi.findPetsByStatus","PetApi.findPetsByTags","PetApi.getPetById","PetApi.updatePet","PetApi.updatePetWithForm","PetApi.uploadFile","StoreApiApiKeys","StoreApi","StoreApi.constructor","StoreApi.setApiKey","StoreApi.accessToken","StoreApi.extendObj","StoreApi.deleteOrder","StoreApi.getInventory","StoreApi.getOrderById","StoreApi.placeOrder","UserApiApiKeys","UserApi","UserApi.constructor","UserApi.setApiKey","UserApi.accessToken","UserApi.extendObj","UserApi.createUser","UserApi.createUsersWithArrayInput","UserApi.createUsersWithListInput","UserApi.deleteUser","UserApi.getUserByName","UserApi.loginUser","UserApi.logoutUser","UserApi.updateUser"],"mappings":"AAAA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,IAAO,OAAO,WAAW,UAAU,CAAC,CAAC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAQtD;IAAAA;IAGAC,CAACA;IAADD,eAACA;AAADA,CAACA,AAHD,IAGC;AAHY,gBAAQ,WAGpB,CAAA;AAED;IAAAE;IAUAC,CAACA;IAADD,YAACA;AAADA,CAACA,AAVD,IAUC;AAVY,aAAK,QAUjB,CAAA;AAED,IAAiB,KAAK,CAMrB;AAND,WAAiB,KAAK,EAAC,CAAC;IACpBA,WAAYA,UAAUA;QAClBE,6CAA0BA,QAAQA,uBAAAA,CAAAA;QAClCA,+CAA4BA,UAAUA,yBAAAA,CAAAA;QACtCA,gDAA6BA,WAAWA,0BAAAA,CAAAA;IAC5CA,CAACA,EAJWF,gBAAUA,KAAVA,gBAAUA,QAIrBA;IAJDA,IAAYA,UAAUA,GAAVA,gBAIXA,CAAAA;AACLA,CAACA,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AACD;IAAAG;IAUAC,CAACA;IAADD,UAACA;AAADA,CAACA,AAVD,IAUC;AAVY,WAAG,MAUf,CAAA;AAED,IAAiB,GAAG,CAMnB;AAND,WAAiB,GAAG,EAAC,CAAC;IAClBA,WAAYA,UAAUA;QAClBE,gDAA6BA,WAAWA,0BAAAA,CAAAA;QACxCA,8CAA2BA,SAASA,wBAAAA,CAAAA;QACpCA,2CAAwBA,MAAMA,qBAAAA,CAAAA;IAClCA,CAACA,EAJWF,cAAUA,KAAVA,cAAUA,QAIrBA;IAJDA,IAAYA,UAAUA,GAAVA,cAIXA,CAAAA;AACLA,CAACA,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AACD;IAAAG;IAGAC,CAACA;IAADD,UAACA;AAADA,CAACA,AAHD,IAGC;AAHY,WAAG,MAGf,CAAA;AAED;IAAAE;IAYAC,CAACA;IAADD,WAACA;AAADA,CAACA,AAZD,IAYC;AAZY,YAAI,OAYhB,CAAA;AAUD;IAAAE;IAQAC,CAACA;IALGD,sCAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,cAAcA,CAACA,IAAIA,GAAGA;YAClBA,QAAQA,EAAEA,IAAIA,CAACA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,CAACA,QAAQA;SACnDA,CAAAA;IACLA,CAACA;IACLF,oBAACA;AAADA,CAACA,AARD,IAQC;AARY,qBAAa,gBAQzB,CAAA;AAED;IAGIG,oBAAoBA,QAAgBA,EAAUA,SAAiBA;QAA3CC,aAAQA,GAARA,QAAQA,CAAQA;QAAUA,cAASA,GAATA,SAASA,CAAQA;IAC/DA,CAACA;IAEDD,mCAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,EAAEA,CAACA,CAACA,IAAIA,CAACA,QAAQA,IAAIA,OAAOA,CAACA,CAACA,CAACA;YACrBA,cAAcA,CAACA,EAAGA,CAACA,IAAIA,CAACA,SAASA,CAACA,GAAGA,IAAIA,CAACA,MAAMA,CAACA;QAC3DA,CAACA;QAACA,IAAIA,CAACA,EAAEA,CAACA,CAACA,IAAIA,CAACA,QAAQA,IAAIA,QAAQA,CAACA,CAACA,CAACA;YACnCA,cAAcA,CAACA,OAAOA,CAACA,IAAIA,CAACA,SAASA,CAACA,GAAGA,IAAIA,CAACA,MAAMA,CAACA;QACzDA,CAACA;IACLA,CAACA;IACLF,iBAACA;AAADA,CAACA,AAbD,IAaC;AAbY,kBAAU,aAatB,CAAA;AAED;IAAAG;IAMAC,CAACA;IAHGD,8BAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,cAAcA,CAACA,OAAOA,CAACA,eAAeA,CAACA,GAAGA,SAASA,GAAGA,IAAIA,CAACA,WAAWA,CAACA;IAC3EA,CAACA;IACLF,YAACA;AAADA,CAACA,AAND,IAMC;AANY,aAAK,QAMjB,CAAA;AAED;IAAAG;IAMAC,CAACA;IAHGD,iCAAcA,GAAdA,UAAeA,cAA+BA;IAE9CE,CAACA;IACLF,eAACA;AAADA,CAACA,AAND,IAMC;AANY,gBAAQ,WAMpB,CAAA;AAED,WAAY,aAAa;IACrBG,uDAAOA,CAAAA;AACXA,CAACA,EAFW,qBAAa,KAAb,qBAAa,QAExB;AAFD,IAAY,aAAa,GAAb,qBAEX,CAAA;AAED;IAWIC,gBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,0BAASA,GAAhBA,UAAiBA,GAAkBA,EAAEA,KAAaA;QAC9CE,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC5DA,CAACA;IAEDF,sBAAIA,+BAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,0BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,uBAAMA,GAAbA,UAAeA,IAAUA;QACrBK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,MAAMA,CAACA;QAC5CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOML,0BAASA,GAAhBA,UAAkBA,KAAaA,EAAEA,MAAeA;QAC5CM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,wEAAwEA,CAACA,CAACA;QAC9FA,CAACA;QAEDA,YAAYA,CAACA,SAASA,CAACA,GAAGA,MAAMA,CAACA;QAEjCA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,iCAAgBA,GAAvBA,UAAyBA,MAAsBA;QAC3CO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,mBAAmBA,CAACA;QACzDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,MAAMA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACvBA,eAAeA,CAACA,QAAQA,CAACA,GAAGA,MAAMA,CAACA;QACvCA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyDA,CAACA;QAC9FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,+BAAcA,GAArBA,UAAuBA,IAAoBA;QACvCQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,iBAAiBA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,eAAeA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QACnCA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyDA,CAACA;QAC9FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMR,2BAAUA,GAAjBA,UAAmBA,KAAaA;QAC5BS,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,yEAAyEA,CAACA,CAACA;QAC/FA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAkDA,CAACA;QACvFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMT,0BAASA,GAAhBA,UAAkBA,IAAUA;QACxBU,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,MAAMA,CAACA;QAC5CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAQMV,kCAAiBA,GAAxBA,UAA0BA,KAAaA,EAAEA,IAAaA,EAAEA,MAAeA;QACnEW,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,gFAAgFA,CAACA,CAACA;QACtGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,UAAUA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QAC9BA,CAACA;QAEDA,EAAEA,CAACA,CAACA,MAAMA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACvBA,UAAUA,CAACA,QAAQA,CAACA,GAAGA,MAAMA,CAACA;QAClCA,CAACA;QAEDA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAQMX,2BAAUA,GAAjBA,UAAmBA,KAAaA,EAAEA,kBAA2BA,EAAEA,IAAUA;QACrEY,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,0BAA0BA;aAC1DA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,yEAAyEA,CAACA,CAACA;QAC/FA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,EAAEA,CAACA,CAACA,kBAAkBA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACnCA,UAAUA,CAACA,oBAAoBA,CAACA,GAAGA,kBAAkBA,CAACA;QAC1DA,CAACA;QAEDA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,UAAUA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QAC9BA,CAACA;QACDA,WAAWA,GAAGA,IAAIA,CAACA;QAEnBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLZ,aAACA;AAADA,CAACA,AA1dD,IA0dC;AA1dY,cAAM,SA0dlB,CAAA;AACD,WAAY,eAAe;IACvBa,2DAAOA,CAAAA;AACXA,CAACA,EAFW,uBAAe,KAAf,uBAAe,QAE1B;AAFD,IAAY,eAAe,GAAf,uBAEX,CAAA;AAED;IAWIC,kBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,4BAASA,GAAhBA,UAAiBA,GAAoBA,EAAEA,KAAaA;QAChDE,IAAIA,CAACA,eAAeA,CAACA,eAAeA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC9DA,CAACA;IAEDF,sBAAIA,iCAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,4BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,8BAAWA,GAAlBA,UAAoBA,OAAeA;QAC/BK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,wBAAwBA;aACxDA,OAAOA,CAACA,GAAGA,GAAGA,SAASA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,OAAOA,CAACA,CAACA,CAACA;QACrDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,OAAOA,KAAKA,IAAIA,IAAIA,OAAOA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAKML,+BAAYA,GAAnBA;QACIM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAACA;QACxDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyEA,CAACA;QAC9GA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,+BAAYA,GAAnBA,UAAqBA,OAAeA;QAChCO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,wBAAwBA;aACxDA,OAAOA,CAACA,GAAGA,GAAGA,SAASA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,OAAOA,CAACA,CAACA,CAACA;QACrDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,OAAOA,KAAKA,IAAIA,IAAIA,OAAOA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,IAAIA,KAAKA,CAACA,6EAA6EA,CAACA,CAACA;QACnGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAoDA,CAACA;QACzFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,6BAAUA,GAAjBA,UAAmBA,IAAYA;QAC3BQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA,CAACA;QACpDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAoDA,CAACA;QACzFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLR,eAACA;AAADA,CAACA,AAxOD,IAwOC;AAxOY,gBAAQ,WAwOpB,CAAA;AACD,WAAY,cAAc;IACtBS,yDAAOA,CAAAA;AACXA,CAACA,EAFW,sBAAc,KAAd,sBAAc,QAEzB;AAFD,IAAY,cAAc,GAAd,sBAEX,CAAA;AAED;IAWIC,iBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,2BAASA,GAAhBA,UAAiBA,GAAmBA,EAAEA,KAAaA;QAC/CE,IAAIA,CAACA,eAAeA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC7DA,CAACA;IAEDF,sBAAIA,gCAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,2BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,4BAAUA,GAAjBA,UAAmBA,IAAWA;QAC1BK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,OAAOA,CAACA;QAC7CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMML,2CAAyBA,GAAhCA,UAAkCA,IAAkBA;QAChDM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,uBAAuBA,CAACA;QAC7DA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,0CAAwBA,GAA/BA,UAAiCA,IAAkBA;QAC/CO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,sBAAsBA,CAACA;QAC5DA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,4BAAUA,GAAjBA,UAAmBA,QAAgBA;QAC/BQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMR,+BAAaA,GAApBA,UAAsBA,QAAgBA;QAClCS,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,+EAA+EA,CAACA,CAACA;QACrGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOMT,2BAASA,GAAhBA,UAAkBA,QAAiBA,EAAEA,QAAiBA;QAClDU,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,aAAaA,CAACA;QACnDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACzBA,eAAeA,CAACA,UAAUA,CAACA,GAAGA,QAAQA,CAACA;QAC3CA,CAACA;QAEDA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACzBA,eAAeA,CAACA,UAAUA,CAACA,GAAGA,QAAQA,CAACA;QAC3CA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAqDA,CAACA;QAC1FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAKMV,4BAAUA,GAAjBA;QACIW,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA,CAACA;QACpDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOMX,4BAAUA,GAAjBA,UAAmBA,QAAgBA,EAAEA,IAAWA;QAC5CY,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLZ,cAACA;AAADA,CAACA,AA7aD,IA6aC;AA7aY,eAAO,UA6anB,CAAA"} \ 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 cc9b954165b..6eaa16cfd97 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -1,6 +1,6 @@ import request = require('request'); import http = require('http'); -import promise = require('bluebird'); +import Promise = require('bluebird'); let defaultBasePath = 'http://petstore.swagger.io/v2'; @@ -128,11 +128,12 @@ export enum PetApiApiKeys { export class PetApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), - 'petstore_auth': new OAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(basePath?: string); @@ -148,6 +149,10 @@ export class PetApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: PetApiApiKeys, value: string) { this.authentications[PetApiApiKeys[key]].apiKey = value; } @@ -177,12 +182,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -198,18 +203,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Deletes a pet @@ -234,12 +240,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -254,18 +260,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Finds Pets by status @@ -285,12 +292,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -305,18 +312,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Finds Pets by tags @@ -336,12 +344,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -356,18 +364,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Find pet by ID @@ -389,19 +398,19 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -411,18 +420,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Update an existing pet @@ -438,12 +448,12 @@ export class PetApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -459,18 +469,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Updates a pet in the store with form data @@ -502,12 +513,12 @@ export class PetApi { formParams['status'] = status; } - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -522,18 +533,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * uploads an image @@ -566,12 +578,12 @@ export class PetApi { } useFormData = true; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -586,18 +598,19 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } export enum StoreApiApiKeys { @@ -607,11 +620,12 @@ export enum StoreApiApiKeys { export class StoreApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), - 'petstore_auth': new OAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(basePath?: string); @@ -627,6 +641,10 @@ export class StoreApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: StoreApiApiKeys, value: string) { this.authentications[StoreApiApiKeys[key]].apiKey = value; } @@ -662,12 +680,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -680,18 +698,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Returns pet inventories by status @@ -706,12 +725,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -726,18 +745,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Find purchase order by ID @@ -759,12 +779,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -777,18 +797,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Place an order for a pet @@ -804,12 +825,12 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -823,18 +844,19 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } export enum UserApiApiKeys { @@ -844,11 +866,12 @@ export enum UserApiApiKeys { export class UserApi { protected basePath = defaultBasePath; protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; protected authentications = { 'default': new VoidAuth(), - 'petstore_auth': new OAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(basePath?: string); @@ -864,6 +887,10 @@ export class UserApi { } } + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + public setApiKey(key: UserApiApiKeys, value: string) { this.authentications[UserApiApiKeys[key]].apiKey = value; } @@ -893,12 +920,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -912,18 +939,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Creates list of users with given input array @@ -939,12 +967,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -958,18 +986,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Creates list of users with given input array @@ -985,12 +1014,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -1004,18 +1033,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Delete user @@ -1037,12 +1067,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1055,18 +1085,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Get user by user name @@ -1088,12 +1119,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1106,18 +1137,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Logs user into the system @@ -1142,12 +1174,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1160,18 +1192,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Logs out current logged in user session @@ -1186,12 +1219,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, }; @@ -1204,18 +1237,19 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } /** * Updated user @@ -1238,12 +1272,12 @@ export class UserApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, uri: localVarPath, + useQuerystring: this._useQuerystring, json: true, body: body, }; @@ -1257,17 +1291,18 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); } else { - localVarDeferred.reject({ response: response, body: body }); + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } } - } + }); }); - return localVarDeferred.promise; } } diff --git a/samples/client/petstore/typescript-node/npm/client.d.ts b/samples/client/petstore/typescript-node/npm/client.d.ts new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/typescript-node/npm/client.ts b/samples/client/petstore/typescript-node/npm/client.ts index 51a7f687e09..488057b9500 100644 --- a/samples/client/petstore/typescript-node/npm/client.ts +++ b/samples/client/petstore/typescript-node/npm/client.ts @@ -3,7 +3,7 @@ import fs = require('fs'); var petApi = new api.PetApi(); petApi.setApiKey(api.PetApiApiKeys.api_key, 'special-key'); -petApi.setApiKey(api.PetApiApiKeys.test_api_key_header, 'query-key'); +//petApi.setApiKey(api.PetApiApiKeys.test_api_key_header, 'query-key'); var tag1 = new api.Tag(); tag1.id = 18291; @@ -25,7 +25,7 @@ petApi.addPet(pet) var newPet = res.body; petId = newPet.id; console.log(`Created pet with ID ${petId}`); - newPet.status = api.Pet.StatusEnum.available; + newPet.status = api.Pet.StatusEnum.StatusEnum_available; return petApi.updatePet(newPet); }) .then((res) => { @@ -42,7 +42,7 @@ petApi.addPet(pet) }) .then((res) => { console.log('Got pet by ID: ' + JSON.stringify(res.body)); - if (res.body.status != api.Pet.StatusEnum.pending) { + if (res.body.status != api.Pet.StatusEnum.StatusEnum_pending) { throw new Error("Unexpected pet status"); } }) @@ -50,7 +50,7 @@ petApi.addPet(pet) console.error(err); exitCode = 1; }) - .finally(() => { + .then(() => { return petApi.deletePet(petId); }) .then((res) => { diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 440f9d15e0a..a07adba556e 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -1,13 +1,17 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201605031634", + "version": "0.0.1-SNAPSHOT.201605241654", "description": "NodeJS client for @swagger/angular2-typescript-petstore", + "repository": "GIT_USER_ID/GIT_REPO_ID", "main": "api.js", "scripts": { - "build": "typings install && tsc" + "postinstall": "typings install", + "clean": "rm -Rf node_modules/ typings/ *.js", + "build": "tsc", + "test": "npm run build && node client.js" }, "author": "Swagger Codegen Contributors", - "license": "MIT", + "license": "Apache-2.0", "dependencies": { "bluebird": "^3.3.5", "request": "^2.72.0" diff --git a/samples/client/petstore/typescript-node/npm/pom.xml b/samples/client/petstore/typescript-node/npm/pom.xml new file mode 100644 index 00000000000..1e4796b6b23 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + com.wordnik + TypeScriptNodeNPMPestoreClientTests + pom + 1.0-SNAPSHOT + TS Node npm Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + npm-run-build + pre-integration-test + + exec + + + npm + + run + build + + + + + npm-test + integration-test + + exec + + + npm + + test + + + + + + + + diff --git a/samples/client/petstore/typescript-node/npm/sample.png b/samples/client/petstore/typescript-node/npm/sample.png new file mode 100644 index 00000000000..c5916f28970 Binary files /dev/null and b/samples/client/petstore/typescript-node/npm/sample.png differ diff --git a/samples/client/petstore/typescript-node/npm/tsconfig.json b/samples/client/petstore/typescript-node/npm/tsconfig.json index 2dd166566e9..9a007e9f866 100644 --- a/samples/client/petstore/typescript-node/npm/tsconfig.json +++ b/samples/client/petstore/typescript-node/npm/tsconfig.json @@ -10,9 +10,10 @@ "noLib": false, "declaration": true }, - "files": [ - "api.ts", - "typings/main.d.ts" + "exclude": [ + "node_modules", + "typings/browser", + "typings/browser.d.ts" ] } diff --git a/samples/client/petstore/typescript-node/npm/typings.json b/samples/client/petstore/typescript-node/npm/typings.json index 76c4cc8e6af..22fcebdc231 100644 --- a/samples/client/petstore/typescript-node/npm/typings.json +++ b/samples/client/petstore/typescript-node/npm/typings.json @@ -1,10 +1,10 @@ { "ambientDependencies": { - "bluebird": "registry:dt/bluebird#2.0.0+20160319051630", "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914" }, "dependencies": { + "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "request": "registry:npm/request#2.69.0+20160304121250" } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/.swagger-codegen-ignore b/samples/server/petstore/jaxrs/jersey1/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/.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 +# Thsi 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/jaxrs/jersey1/LICENSE b/samples/server/petstore/jaxrs/jersey1/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/server/petstore/jaxrs/README.md b/samples/server/petstore/jaxrs/jersey1/README.md similarity index 100% rename from samples/server/petstore/jaxrs/README.md rename to samples/server/petstore/jaxrs/jersey1/README.md diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/jersey1/pom.xml similarity index 93% rename from samples/server/petstore/jaxrs/pom.xml rename to samples/server/petstore/jaxrs/jersey1/pom.xml index 9064489b34d..4fb015cf78c 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/jersey1/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-jaxrs-server + swagger-jaxrs-jersey1-server jar - swagger-jaxrs-server + swagger-jaxrs-jersey1-server 1.0.0 src/main/java @@ -168,11 +168,12 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 - 1.18.1 - 1.6.3 - 4.8.1 + 1.19.1 + 1.7.21 + 4.12 2.5 + UTF-8 - \ No newline at end of file + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/JacksonJsonProvider.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StringUtil.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..f76411d073a --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Category { + + private Long id = null; + private String name = null; + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(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); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java similarity index 79% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java index ac9fb970f82..9c61a7434e7 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -2,6 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; -public class ApiResponse { +public class ModelApiResponse { private Integer code = null; private String type = null; @@ -18,7 +19,7 @@ public class ApiResponse { /** **/ - public ApiResponse code(Integer code) { + public ModelApiResponse code(Integer code) { this.code = code; return this; } @@ -35,7 +36,7 @@ public class ApiResponse { /** **/ - public ApiResponse type(String type) { + public ModelApiResponse type(String type) { this.type = type; return this; } @@ -52,7 +53,7 @@ public class ApiResponse { /** **/ - public ApiResponse message(String message) { + public ModelApiResponse message(String message) { this.message = message; return this; } @@ -76,10 +77,10 @@ public class ApiResponse { if (o == null || getClass() != o.getClass()) { return false; } - ApiResponse apiResponse = (ApiResponse) o; - return Objects.equals(code, apiResponse.code) && - Objects.equals(type, apiResponse.type) && - Objects.equals(message, apiResponse.message); + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); } @Override @@ -90,7 +91,7 @@ public class ApiResponse { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class ApiResponse {\n"); + sb.append("class ModelApiResponse {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java rename to samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..f203b01f55b --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Tag { + + private Long id = null; + private String name = null; + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(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); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..f239bb3febc --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,215 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(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); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/Bootstrap.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java similarity index 68% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index 8a15fd9a8ad..54ae4b48435 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java similarity index 69% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 4f83a413c6f..79a403fee06 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java similarity index 69% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 0ce96e28a30..2f1ae542f1b 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java similarity index 92% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index a6183190212..0dc50dd1fcc 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,8 +6,8 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; -import io.swagger.model.ApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -20,63 +20,54 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class PetApiServiceImpl extends PetApiService { - @Override public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response findPetsByStatus(List status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response findPetsByTags(List tags, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java similarity index 90% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index d347d2b8f1f..2b00aa8fad0 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -19,35 +19,30 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class StoreApiServiceImpl extends StoreApiService { - @Override public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response getInventory(SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response getOrderById(Long orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java similarity index 93% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java rename to samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 5a73ac74e73..902658f35a8 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -19,63 +19,54 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") + public class UserApiServiceImpl extends UserApiService { - @Override public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response loginUser(String username, String password, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response logoutUser(SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - @Override public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - } diff --git a/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs/jersey1/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml rename to samples/server/petstore/jaxrs/jersey1/src/main/webapp/WEB-INF/web.xml diff --git a/samples/server/petstore/jaxrs/jersey2/.swagger-codegen-ignore b/samples/server/petstore/jaxrs/jersey2/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/.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 +# Thsi 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/jaxrs/jersey2/LICENSE b/samples/server/petstore/jaxrs/jersey2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/server/petstore/jaxrs/jersey2/README.md b/samples/server/petstore/jaxrs/jersey2/README.md new file mode 100644 index 00000000000..4e7da8b7f63 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/README.md @@ -0,0 +1,23 @@ +# Swagger Jersey 2 generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled JAX-RS server. + +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +To run the server, please execute the following: + +``` +mvn clean package jetty:run +``` + +You can then view the swagger listing here: + +``` +http://localhost:8080/v2/swagger.json +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml new file mode 100644 index 00000000000..d1772e4f5e7 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -0,0 +1,146 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-server + jar + swagger-jaxrs-server + 1.0.0 + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + 8080 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey2-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey2-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey2-version} + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.5.9 + 9.2.9.v20150224 + 2.22.2 + 1.7.21 + 4.12 + 1.1.7 + 2.5 + UTF-8 + + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..97e535d3c21 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..38791eef046 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,22 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() {} + + public void init(FilterConfig filterConfig) throws ServletException {} +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..87db95c1009 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement + +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java new file mode 100644 index 00000000000..49792814c5e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import io.swagger.util.Json; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + private static ObjectMapper commonMapper = Json.mapper(); + + public JacksonJsonProvider() { + super.setMapper(commonMapper); + } +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..b28b67ea4b2 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..791d56e9eeb --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,173 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/pet") + + +@io.swagger.annotations.Api(description = "the pet API") + +public class PetApi { + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.addPet(body,securityContext); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deletePet(petId,apiKey,securityContext); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata, + @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java new file mode 100644 index 00000000000..e472a575fae --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -0,0 +1,30 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class PetApiService { + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException; + public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..7319e0465f0 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,87 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/store") + + +@io.swagger.annotations.Api(description = "the store API") + +public class StoreApi { + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java new file mode 100644 index 00000000000..5ef766d6aa7 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -0,0 +1,25 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class StoreApiService { + public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById(Long orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java new file mode 100644 index 00000000000..6f4a3dadbbf --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.api; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..ed3d4e4ead4 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,131 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/user") + + +@io.swagger.annotations.Api(description = "the user API") + +public class UserApi { + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUser(body,securityContext); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithArrayInput(body,securityContext); + } + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithListInput(body,securityContext); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username,@ApiParam(value = "Updated user object" ,required=true) User body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updateUser(username,body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java new file mode 100644 index 00000000000..ceff72b6391 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -0,0 +1,29 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class UserApiService { + public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; + public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; + public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java rename to samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ModelApiResponse.java rename to samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..825fa282b8b --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,196 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + + + + + + +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + + + public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + private Boolean complete = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(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); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..24092cbee25 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,199 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + + + + +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + + + public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(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); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java rename to samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java similarity index 100% rename from samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java rename to samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java new file mode 100644 index 00000000000..1f60ed6cf4b --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("Swagger Server") + .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(new Contact() + .email("apiteam@swagger.io")) + .license(new License() + .name("Apache 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0.html")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java new file mode 100644 index 00000000000..43321e8c0e9 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.PetApiService; +import io.swagger.api.impl.PetApiServiceImpl; + + +public class PetApiServiceFactory { + private final static PetApiService service = new PetApiServiceImpl(); + + public static PetApiService getPetApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java new file mode 100644 index 00000000000..254fd0a9a7d --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.StoreApiService; +import io.swagger.api.impl.StoreApiServiceImpl; + + +public class StoreApiServiceFactory { + private final static StoreApiService service = new StoreApiServiceImpl(); + + public static StoreApiService getStoreApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java new file mode 100644 index 00000000000..4c50105bb50 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.UserApiService; +import io.swagger.api.impl.UserApiServiceImpl; + + +public class UserApiServiceFactory { + private final static UserApiService service = new UserApiServiceImpl(); + + public static UserApiService getUserApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..9c9b7b6c23b --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,62 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class PetApiServiceImpl extends PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..85e14b0bbe5 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,41 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class StoreApiServiceImpl extends StoreApiService { + @Override + public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..67bdeb908f6 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,61 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class UserApiServiceImpl extends UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs/jersey2/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..66837dccab8 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,63 @@ + + + + + jersey + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + + io.swagger.jaxrs.listing, + io.swagger.sample.resource, + io.swagger.api + + + + jersey.config.server.provider.classnames + org.glassfish.jersey.media.multipart.MultiPartFeature + + + jersey.config.server.wadl.disableWadl + true + + 1 + + + + Jersey2Config + io.swagger.jersey.config.JerseyJaxrsConfig + + api.version + 1.0.0 + + + swagger.api.title + Swagger Server + + + swagger.api.basepath + http://petstore.swagger.io/v2 + + + 2 + + + Bootstrap + io.swagger.api.Bootstrap + 2 + + + jersey + /v2/* + + + ApiOriginFilter + io.swagger.api.ApiOriginFilter + + + ApiOriginFilter + /* + + diff --git a/samples/server/petstore/nodejs/api/swagger.yaml b/samples/server/petstore/nodejs/api/swagger.yaml index f6987daa915..1aad0a1d4f4 100644 --- a/samples/server/petstore/nodejs/api/swagger.yaml +++ b/samples/server/petstore/nodejs/api/swagger.yaml @@ -587,6 +587,10 @@ paths: description: "User not found" x-swagger-router-controller: "User" securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -594,10 +598,6 @@ securityDefinitions: 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" diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index 2c464714aa7..55a4bf2b896 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -26,18 +26,18 @@ exports.findPetsByStatus = function(args, res, next) { **/ var examples = {}; examples['application/json'] = [ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] } ]; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -56,18 +56,18 @@ exports.findPetsByTags = function(args, res, next) { **/ var examples = {}; examples['application/json'] = [ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] } ]; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -86,18 +86,18 @@ exports.getPetById = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -138,9 +138,9 @@ exports.uploadFile = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { + "message" : "aeiou", "code" : 123, - "type" : "aeiou", - "message" : "aeiou" + "type" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index d20619ceb9b..01759173bd4 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -34,12 +34,12 @@ exports.getOrderById = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "petId" : 123456789, - "quantity" : 123, "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -58,12 +58,12 @@ exports.placeOrder = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "petId" : 123456789, - "quantity" : 123, "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js index 3a62feeaf3f..69fc1a81391 100644 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -43,14 +43,14 @@ exports.getUserByName = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "firstName" : "aeiou", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index c5884b196b9..0238a86860a 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -6,7 +6,7 @@ "keywords": [ "swagger" ], - "license": "MIT", + "license": "Apache-2.0", "private": true, "dependencies": { "connect": "^3.2.0", diff --git a/samples/server/petstore/rails5/.swagger-codegen-ignore b/samples/server/petstore/rails5/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/rails5/.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 +# Thsi 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/rails5/Gemfile b/samples/server/petstore/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/samples/server/petstore/rails5/Gemfile.lock b/samples/server/petstore/rails5/Gemfile.lock new file mode 100644 index 00000000000..f544bc0f702 --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile.lock @@ -0,0 +1,141 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + nio4r (~> 1.2) + websocket-driver (~> 0.6.1) + actionmailer (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 1.0, >= 1.0.5) + actionpack (5.0.0.rc1) + actionview (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + rack (~> 2.x) + rack-test (~> 0.6.3) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + builder (~> 3.1) + erubis (~> 2.7.0) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + activejob (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + globalid (>= 0.3.6) + activemodel (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + activerecord (5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + arel (~> 7.0) + activesupport (5.0.0.rc1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (~> 0.7) + minitest (~> 5.1) + tzinfo (~> 1.1) + arel (7.0.0) + builder (3.2.2) + byebug (9.0.0) + concurrent-ruby (1.0.2) + erubis (2.7.0) + ffi (1.9.10) + globalid (0.3.6) + activesupport (>= 4.1.0) + i18n (0.7.0) + jbuilder (2.4.1) + activesupport (>= 3.0.0, < 5.1) + multi_json (~> 1.2) + json (1.8.3) + listen (3.0.7) + rb-fsevent (>= 0.9.3) + rb-inotify (>= 0.9.7) + loofah (2.0.3) + nokogiri (>= 1.5.9) + mail (2.6.4) + mime-types (>= 1.16, < 4) + method_source (0.8.2) + mime-types (3.0) + mime-types-data (~> 3.2015) + mime-types-data (3.2016.0221) + mini_portile2 (2.0.0) + minitest (5.8.4) + multi_json (1.12.0) + mysql2 (0.4.4) + nio4r (1.2.1) + nokogiri (1.6.7.2) + mini_portile2 (~> 2.0.0.rc2) + puma (3.4.0) + rack (2.0.0.rc1) + json + rack-test (0.6.3) + rack (>= 1.0) + rails (5.0.0.rc1) + actioncable (= 5.0.0.rc1) + actionmailer (= 5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activerecord (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + bundler (>= 1.3.0, < 2.0) + railties (= 5.0.0.rc1) + sprockets-rails (>= 2.0.0) + rails-deprecated_sanitizer (1.0.3) + activesupport (>= 4.2.0.alpha) + rails-dom-testing (1.0.7) + activesupport (>= 4.2.0.beta, < 5.0) + nokogiri (~> 1.6.0) + rails-deprecated_sanitizer (>= 1.0.1) + rails-html-sanitizer (1.0.3) + loofah (~> 2.0) + railties (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + method_source + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (11.1.2) + rb-fsevent (0.9.7) + rb-inotify (0.9.7) + ffi (>= 0.5.0) + spring (1.7.1) + spring-watcher-listen (2.0.0) + listen (>= 2.7, < 4.0) + spring (~> 1.2) + sprockets (3.6.0) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.0.4) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.19.1) + thread_safe (0.3.5) + tzinfo (1.2.2) + thread_safe (~> 0.1) + websocket-driver (0.6.3) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.2) + +PLATFORMS + ruby + +DEPENDENCIES + byebug + jbuilder (~> 2.0) + listen (~> 3.0.5) + mysql2 (>= 0.3.18, < 0.5) + puma (~> 3.0) + rails (>= 5.0.0.racecar1, < 5.1) + spring + spring-watcher-listen (~> 2.0.0) + tzinfo-data + +BUNDLED WITH + 1.11.2 diff --git a/samples/server/petstore/rails5/LICENSE b/samples/server/petstore/rails5/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/rails5/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/server/petstore/rails5/README.md b/samples/server/petstore/rails5/README.md new file mode 100644 index 00000000000..841b82ad656 --- /dev/null +++ b/samples/server/petstore/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create db:migrate +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/samples/server/petstore/rails5/Rakefile b/samples/server/petstore/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/samples/server/petstore/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/samples/server/petstore/rails5/app/channels/application_cable/channel.rb b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/samples/server/petstore/rails5/app/channels/application_cable/connection.rb b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/samples/server/petstore/rails5/app/controllers/application_controller.rb b/samples/server/petstore/rails5/app/controllers/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/samples/server/petstore/rails5/app/controllers/pet_controllers.rb b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb new file mode 100644 index 00000000000..de0ce998eeb --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb @@ -0,0 +1,72 @@ +=begin +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 +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. + +=end +class PetController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_status + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_tags + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet_with_form + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def upload_file + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/store_controllers.rb b/samples/server/petstore/rails5/app/controllers/store_controllers.rb new file mode 100644 index 00000000000..3c59b24f711 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/store_controllers.rb @@ -0,0 +1,48 @@ +=begin +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 +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. + +=end +class StoreController < ApplicationController + + def delete_order + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_inventory + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_order_by_id + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def place_order + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/user_controllers.rb b/samples/server/petstore/rails5/app/controllers/user_controllers.rb new file mode 100644 index 00000000000..d9e20f887b6 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/user_controllers.rb @@ -0,0 +1,72 @@ +=begin +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 +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. + +=end +class UserController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_array_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_list_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def login_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def logout_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/jobs/application_job.rb b/samples/server/petstore/rails5/app/jobs/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/samples/server/petstore/rails5/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/samples/server/petstore/rails5/app/mailers/application_mailer.rb b/samples/server/petstore/rails5/app/mailers/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/samples/server/petstore/rails5/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/samples/server/petstore/rails5/app/models/api_response.rb b/samples/server/petstore/rails5/app/models/api_response.rb new file mode 100644 index 00000000000..1ad59e6c792 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/api_response.rb @@ -0,0 +1,27 @@ +=begin +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 +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. + +=end + + +class ApiResponse < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/application_record.rb b/samples/server/petstore/rails5/app/models/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/samples/server/petstore/rails5/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/samples/server/petstore/rails5/app/models/category.rb b/samples/server/petstore/rails5/app/models/category.rb new file mode 100644 index 00000000000..3adaa488309 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/category.rb @@ -0,0 +1,27 @@ +=begin +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 +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. + +=end + + +class Category < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/order.rb b/samples/server/petstore/rails5/app/models/order.rb new file mode 100644 index 00000000000..963eb8e18ed --- /dev/null +++ b/samples/server/petstore/rails5/app/models/order.rb @@ -0,0 +1,27 @@ +=begin +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 +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. + +=end + + +class Order < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/pet.rb b/samples/server/petstore/rails5/app/models/pet.rb new file mode 100644 index 00000000000..da927b6260e --- /dev/null +++ b/samples/server/petstore/rails5/app/models/pet.rb @@ -0,0 +1,31 @@ +=begin +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 +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. + +=end + + +class Pet < ApplicationRecord + validate_presence_of :name + validate_presence_of :photo_urls + + serialize :photo_urls, Array + serialize :tags, Array +end diff --git a/samples/server/petstore/rails5/app/models/tag.rb b/samples/server/petstore/rails5/app/models/tag.rb new file mode 100644 index 00000000000..096f132e2c2 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/tag.rb @@ -0,0 +1,27 @@ +=begin +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 +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. + +=end + + +class Tag < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/user.rb b/samples/server/petstore/rails5/app/models/user.rb new file mode 100644 index 00000000000..47f81df1089 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/user.rb @@ -0,0 +1,27 @@ +=begin +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 +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. + +=end + + +class User < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/samples/server/petstore/rails5/bin/bundle b/samples/server/petstore/rails5/bin/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/samples/server/petstore/rails5/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/samples/server/petstore/rails5/bin/rails b/samples/server/petstore/rails5/bin/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/samples/server/petstore/rails5/bin/rake b/samples/server/petstore/rails5/bin/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/samples/server/petstore/rails5/bin/setup b/samples/server/petstore/rails5/bin/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/samples/server/petstore/rails5/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/bin/update b/samples/server/petstore/rails5/bin/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/samples/server/petstore/rails5/bin/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/config.ru b/samples/server/petstore/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/samples/server/petstore/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/samples/server/petstore/rails5/config/application.rb b/samples/server/petstore/rails5/config/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/samples/server/petstore/rails5/config/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/samples/server/petstore/rails5/config/boot.rb b/samples/server/petstore/rails5/config/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/samples/server/petstore/rails5/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/samples/server/petstore/rails5/config/cable.yml b/samples/server/petstore/rails5/config/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/samples/server/petstore/rails5/config/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/samples/server/petstore/rails5/config/config/development.rb b/samples/server/petstore/rails5/config/config/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/samples/server/petstore/rails5/config/config/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/samples/server/petstore/rails5/config/config/production.rb b/samples/server/petstore/rails5/config/config/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/samples/server/petstore/rails5/config/config/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/samples/server/petstore/rails5/config/database.yml b/samples/server/petstore/rails5/config/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/samples/server/petstore/rails5/config/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/samples/server/petstore/rails5/config/environment.rb b/samples/server/petstore/rails5/config/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/samples/server/petstore/rails5/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/samples/server/petstore/rails5/config/initializers/callback_terminator.rb b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/samples/server/petstore/rails5/config/initializers/cors.rb b/samples/server/petstore/rails5/config/initializers/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/samples/server/petstore/rails5/config/initializers/inflections.rb b/samples/server/petstore/rails5/config/initializers/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/samples/server/petstore/rails5/config/initializers/mime_types.rb b/samples/server/petstore/rails5/config/initializers/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/samples/server/petstore/rails5/config/initializers/ssl_options.rb b/samples/server/petstore/rails5/config/initializers/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/samples/server/petstore/rails5/config/locales/en.yml b/samples/server/petstore/rails5/config/locales/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/samples/server/petstore/rails5/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/samples/server/petstore/rails5/config/puma.rb b/samples/server/petstore/rails5/config/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/samples/server/petstore/rails5/config/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/samples/server/petstore/rails5/config/routes.rb b/samples/server/petstore/rails5/config/routes.rb new file mode 100644 index 00000000000..f396a612ec2 --- /dev/null +++ b/samples/server/petstore/rails5/config/routes.rb @@ -0,0 +1,50 @@ +=begin +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 +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. + +=end +Rails.application.routes.draw do + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method + end + + add_swagger_route 'POST', '/v2/pet', controller_name: 'pet', action_name: 'create' + add_swagger_route 'DELETE', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'destroy' + add_swagger_route 'GET', '/v2/pet/findByStatus', controller_name: 'pet', action_name: 'find_pets_by_status' + add_swagger_route 'GET', '/v2/pet/findByTags', controller_name: 'pet', action_name: 'find_pets_by_tags' + add_swagger_route 'GET', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'show' + add_swagger_route 'PUT', '/v2/pet', controller_name: 'pet', action_name: 'update_pet' + add_swagger_route 'POST', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'update_pet_with_form' + add_swagger_route 'POST', '/v2/pet/{petId}/uploadImage', controller_name: 'pet', action_name: 'upload_file' + add_swagger_route 'DELETE', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'delete_order' + add_swagger_route 'GET', '/v2/store/inventory', controller_name: 'store', action_name: 'get_inventory' + add_swagger_route 'GET', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'get_order_by_id' + add_swagger_route 'POST', '/v2/store/order', controller_name: 'store', action_name: 'place_order' + add_swagger_route 'POST', '/v2/user', controller_name: 'user', action_name: 'create' + add_swagger_route 'POST', '/v2/user/createWithArray', controller_name: 'user', action_name: 'create_users_with_array_input' + add_swagger_route 'POST', '/v2/user/createWithList', controller_name: 'user', action_name: 'create_users_with_list_input' + add_swagger_route 'DELETE', '/v2/user/{username}', controller_name: 'user', action_name: 'destroy' + add_swagger_route 'GET', '/v2/user/{username}', controller_name: 'user', action_name: 'show' + add_swagger_route 'GET', '/v2/user/login', controller_name: 'user', action_name: 'login_user' + add_swagger_route 'GET', '/v2/user/logout', controller_name: 'user', action_name: 'logout_user' + add_swagger_route 'PUT', '/v2/user/{username}', controller_name: 'user', action_name: 'update' +end diff --git a/samples/server/petstore/rails5/config/secrets.yml b/samples/server/petstore/rails5/config/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/samples/server/petstore/rails5/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/samples/server/petstore/rails5/config/spring.rb b/samples/server/petstore/rails5/config/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/samples/server/petstore/rails5/config/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/samples/server/petstore/rails5/db/migrate/.keep b/samples/server/petstore/rails5/db/migrate/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb new file mode 100644 index 00000000000..5fa060fb4dc --- /dev/null +++ b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb @@ -0,0 +1,84 @@ +=begin +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 +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. + +=end + +class InitTables < ActiveRecord::Migration + def change + create_table :api_response, id: false do |t| + t.integer :code + t.string :type + t.string :message + + t.timestamps + end + + create_table :category, id: false do |t| + t.integer :id + t.string :name + + t.timestamps + end + + create_table :order, id: false do |t| + t.integer :id + t.integer :pet_id + t.integer :quantity + t.datetime :ship_date + t.string :status + t.boolean :complete + + t.timestamps + end + + create_table :pet, id: false do |t| + t.integer :id + t.string :category + t.string :name + t.string :photo_urls + t.string :tags + t.string :status + + t.timestamps + end + + create_table :tag, id: false do |t| + t.integer :id + t.string :name + + t.timestamps + end + + create_table :user, id: false do |t| + t.integer :id + t.string :username + t.string :first_name + t.string :last_name + t.string :email + t.string :password + t.string :phone + t.integer :user_status + + t.timestamps + end + + end +end diff --git a/samples/server/petstore/rails5/db/schema.rb b/samples/server/petstore/rails5/db/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/samples/server/petstore/rails5/db/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/samples/server/petstore/rails5/db/seeds.rb b/samples/server/petstore/rails5/db/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/samples/server/petstore/rails5/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/samples/server/petstore/rails5/lib/tasks/.keep b/samples/server/petstore/rails5/lib/tasks/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/.keep b/samples/server/petstore/rails5/log/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/development.log b/samples/server/petstore/rails5/log/development.log new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/404.html b/samples/server/petstore/rails5/public/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/samples/server/petstore/rails5/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/422.html b/samples/server/petstore/rails5/public/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/samples/server/petstore/rails5/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/500.html b/samples/server/petstore/rails5/public/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/samples/server/petstore/rails5/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png b/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/apple-touch-icon.png b/samples/server/petstore/rails5/public/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/favicon.ico b/samples/server/petstore/rails5/public/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/robots.txt b/samples/server/petstore/rails5/public/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/samples/server/petstore/rails5/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/samples/server/petstore/rails5/test/test_helper.rb b/samples/server/petstore/rails5/test/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/samples/server/petstore/rails5/test/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/samples/server/petstore/rails5/tmp/cache/.keep b/samples/server/petstore/rails5/tmp/cache/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/pids/.keep b/samples/server/petstore/rails5/tmp/pids/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/restart.txt b/samples/server/petstore/rails5/tmp/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/sockets/.keep b/samples/server/petstore/rails5/tmp/sockets/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/vendor/.keep b/samples/server/petstore/rails5/vendor/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/sinatra/.swagger-codegen-ignore b/samples/server/petstore/sinatra/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/sinatra/.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 +# Thsi 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/sinatra/LICENSE b/samples/server/petstore/sinatra/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/sinatra/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/server/petstore/slim/.swagger-codegen-ignore b/samples/server/petstore/slim/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/slim/.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 +# Thsi 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/slim/LICENSE b/samples/server/petstore/slim/LICENSE new file mode 100644 index 00000000000..d9a10c0d8e8 --- /dev/null +++ b/samples/server/petstore/slim/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/samples/server/petstore/spring-mvc-j8-async/pom.xml b/samples/server/petstore/spring-mvc-j8-async/pom.xml index 1c535f34084..767c386463f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/pom.xml +++ b/samples/server/petstore/spring-mvc-j8-async/pom.xml @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java index 608a7957017..041a8a204f3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java index 0a2894d0be4..1276b3cfab0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java index 9bc56631d29..4859dc5c6c4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java index 72ca217e7c0..67027e9eb9e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index c3d4887b35f..363b8deee1d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -3,6 +3,7 @@ package io.swagger.api; import io.swagger.model.*; import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; import java.io.File; import java.util.concurrent.Callable; @@ -34,7 +35,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @@ -46,12 +47,12 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) default Callable> addPet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -68,7 +69,7 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deletePet( @@ -85,7 +86,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -95,10 +96,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid status value") }) @RequestMapping(value = "/findByStatus", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status ) @@ -108,7 +109,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -118,10 +119,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid tag value") }) @RequestMapping(value = "/findByTags", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags ) @@ -131,11 +132,7 @@ public interface PetApi { } - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }), + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") }) @ApiResponses(value = { @@ -143,11 +140,11 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getPetById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { @@ -167,12 +164,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) default Callable> updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -189,11 +186,11 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) default Callable> updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId , @@ -212,7 +209,7 @@ public interface PetApi { } - @ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -221,10 +218,10 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - default Callable> uploadFile( + default Callable> uploadFile( @ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId , @@ -239,7 +236,7 @@ public interface PetApi { ) throws NotFoundException { // do some magic! - return () -> new ResponseEntity(HttpStatus.OK); + return () -> new ResponseEntity(HttpStatus.OK); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index 4eb6c73849a..f5c454b68e1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @@ -42,7 +42,7 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteOrder( @@ -61,7 +61,7 @@ public interface StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/inventory", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, method = RequestMethod.GET) default Callable>> getInventory() @@ -77,11 +77,11 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId ) throws NotFoundException { @@ -95,12 +95,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid Order") }) @RequestMapping(value = "/order", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) @RequestBody Order body +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index b24082923dc..7141c53284d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -34,19 +34,19 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUser( -@ApiParam(value = "Created user object" ) @RequestBody User body +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! @@ -58,12 +58,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithArray", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -75,12 +75,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithList", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithListInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -93,7 +93,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteUser( @@ -112,7 +112,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getUserByName( @@ -130,14 +130,14 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) @RequestMapping(value = "/login", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable> loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + default Callable> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username , - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password ) @@ -151,7 +151,7 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/logout", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> logoutUser() @@ -166,7 +166,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) default Callable> updateUser( @@ -175,7 +175,7 @@ public interface UserApi { , -@ApiParam(value = "Updated user object" ) @RequestBody User body +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java index 5004845542f..3b3f1c4e719 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -20,18 +20,18 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .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") + .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.") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") .version("1.0.0") - .contact(new Contact("","", "apiteam@wordnik.com")) + .contact(new Contact("","", "apiteam@swagger.io")) .build(); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index 6b3b305942f..b68e3a5d9f8 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java index 7e437ae6b14..e99cfea70a2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 40f8a10a438..70ad7190474 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 18f08f895e1..e9d8c1ffed0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..61d9bc8be58 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,84 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(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); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index 738a9e81f96..8ea322ac31d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Order { private Long id = null; @@ -23,7 +23,7 @@ public class Order { }; private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** **/ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 26e4d3c529e..482e8e16097 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -14,7 +14,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index 2f39f45a1f8..895fb2a7e1f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index eee7800acbf..5620b9d4b72 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/springboot/.swagger-codegen-ignore b/samples/server/petstore/springboot/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/springboot/.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 +# Thsi 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/springboot/LICENSE b/samples/server/petstore/springboot/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/springboot/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/samples/server/petstore/springboot/README.md b/samples/server/petstore/springboot/README.md index 8f9855eedf9..a2e8a9f7b84 100644 --- a/samples/server/petstore/springboot/README.md +++ b/samples/server/petstore/springboot/README.md @@ -15,4 +15,4 @@ Start your server as an simple java application You can view the api documentation in swagger-ui by pointing to http://localhost:8080/ -Change default port value in application.properties \ No newline at end of file +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot/pom.xml b/samples/server/petstore/springboot/pom.xml index 139b3da9ab4..0002871db8f 100644 --- a/samples/server/petstore/springboot/pom.xml +++ b/samples/server/petstore/springboot/pom.xml @@ -50,5 +50,14 @@ springfox-swagger-ui ${springfox-version}
+ + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java index 2cc65db2b81..4317ba2f1a6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -33,4 +33,4 @@ public class Swagger2SpringBoot implements CommandLineRunner { } } -} \ No newline at end of file +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java index 1652afba0ad..7fa61c50d24 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java index d18415d8e7c..f0f62dc7206 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java index a58b9c19e97..33f95878e54 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java index 8770f484be1..295109d7fc4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 7f66bdc75f7..bb63b7e11d6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -3,14 +3,12 @@ package io.swagger.api; import io.swagger.model.*; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -24,11 +22,9 @@ import java.util.List; import static org.springframework.http.MediaType.*; -@Controller -@RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) -@Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") -public class PetApi { +@Api(value = "pet", description = "the pet API") + +public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @@ -38,18 +34,11 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - @RequestMapping(value = "", + @RequestMapping(value = "/pet", produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity addPet( - -@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -60,22 +49,11 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - @RequestMapping(value = "/{petId}", + @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, - method = RequestMethod.DELETE) - public ResponseEntity deletePet( -@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId - -, - -@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -87,18 +65,10 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) - @RequestMapping(value = "/findByStatus", + @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status - - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); - } + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -110,18 +80,10 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) - @RequestMapping(value = "/findByTags", + @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags - - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); - } + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -131,18 +93,10 @@ public class PetApi { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - @RequestMapping(value = "/{petId}", + @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity getPetById( -@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -155,18 +109,11 @@ public class PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) - @RequestMapping(value = "", + @RequestMapping(value = "/pet", produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updatePet( - -@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -177,28 +124,13 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - @RequestMapping(value = "/{petId}", + @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - public ResponseEntity updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId - -, - - - -@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name -, - - - -@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -209,26 +141,12 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) - @RequestMapping(value = "/{petId}/uploadImage", + @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - public ResponseEntity uploadFile( -@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId - -, - - - -@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata -, - - -@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..ec3bbf3e747 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,71 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class PetApiController implements PetApi { + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index 8cf2283e4fe..2fb7585dbdd 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,7 @@ import io.swagger.model.Order; import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -23,28 +21,18 @@ import java.util.List; import static org.springframework.http.MediaType.*; -@Controller -@RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) -@Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") -public class StoreApi { +@Api(value = "store", description = "the store API") + +public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) - @RequestMapping(value = "/order/{orderId}", + @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, - method = RequestMethod.DELETE) - public ResponseEntity deleteOrder( -@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -52,15 +40,10 @@ public class StoreApi { }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) - @RequestMapping(value = "/inventory", + @RequestMapping(value = "/store/inventory", produces = { "application/json" }, - method = RequestMethod.GET) - public ResponseEntity> getInventory() - throws NotFoundException { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); - } + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @@ -68,35 +51,19 @@ public class StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - @RequestMapping(value = "/order/{orderId}", + @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - @RequestMapping(value = "/order", + @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, - method = RequestMethod.POST) - public ResponseEntity placeOrder( - -@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..92de5eb86b4 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,45 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class StoreApiController implements StoreApi { + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index 36c500faded..3877be4e8ad 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,7 @@ import java.util.List; import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -23,79 +21,45 @@ import java.util.List; import static org.springframework.http.MediaType.*; -@Controller -@RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) -@Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") -public class UserApi { +@Api(value = "user", description = "the user API") + +public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "", + @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, - method = RequestMethod.POST) - public ResponseEntity createUser( - -@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/createWithArray", + @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, - method = RequestMethod.POST) - public ResponseEntity createUsersWithArrayInput( - -@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/createWithList", + @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, - method = RequestMethod.POST) - public ResponseEntity createUsersWithListInput( - -@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) - @RequestMapping(value = "/{username}", + @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, - method = RequestMethod.DELETE) - public ResponseEntity deleteUser( -@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", notes = "", response = User.class) @@ -103,75 +67,40 @@ public class UserApi { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @ApiResponse(code = 404, message = "User not found", response = User.class) }) - @RequestMapping(value = "/{username}", + @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity getUserByName( -@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - @RequestMapping(value = "/login", + @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username - - -, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password - - -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/logout", + @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity logoutUser() - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) - @RequestMapping(value = "/{username}", + @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, - method = RequestMethod.PUT) - public ResponseEntity updateUser( -@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username - -, - - -@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body -) - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..f855d358ea5 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,67 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.List; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class UserApiController implements UserApi { + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index 185c0e08794..282773a2d30 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -13,7 +13,7 @@ import springfox.documentation.spring.web.plugins.Docket; @Configuration -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class SwaggerDocumentationConfig { ApiInfo apiInfo() { @@ -34,6 +34,8 @@ public class SwaggerDocumentationConfig { .select() .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) .build() + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java index 411a206a7f6..d7aa14a8c75 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class Category { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java index 73a0717d5e5..50163623706 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class ModelApiResponse { private Integer code = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index 3f8bbd49e37..941bfe67c2f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @@ -13,13 +13,13 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; public enum StatusEnum { placed, approved, delivered, }; @@ -64,10 +64,10 @@ public class Order { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index 1507c988f3b..aabffb593e4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -16,7 +16,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class Pet { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index 665a5c00270..e9ef2ca5704 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class Tag { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index dd8cd876e7b..76ac713c8ee 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") + public class User { private Long id = null;